0

Does a class in RoR automatically initiate the first method when a new object of that class is created?

class User
 attr_accessor :name, :email

 def initialize(attributes = {})
  @name  = attributes[:name]
  @email = attributes[:email]
 end

 def formatted_email
  "#{@name} <#{@email}>"
 end
end

Say I create a new User like this

connor = User.new(name: "Connor B", email: "CB@example.com")

How does it know to automatically start the first method but the second method only works when called upon?

jefflunt
  • 33,527
  • 7
  • 88
  • 126

2 Answers2

5

It's not the first method that's called automatically, it's that new calls initialize, which happens to be the first method in most code that you see. However, you could put initialize anywhere in the class definition and new would still call the initialize method.

If there is no initialize method explicitly defined then a default one will be called. Also, this is a Ruby behavior, not a Ruby on Rails behavior, just to clarify.

Here's a related Q&A that you might find enlightening. The top answer shows an example that explains it in a bit more detail, and digs into more of what's actually going on behind the scenes.

Community
  • 1
  • 1
jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • Okay that makes sense. So every class by default has an initialize method. – Connor Besancenez Jan 05 '15 at 00:53
  • You can think of it that way, sure. There's some more detail in this Q&A (which I've added to my answer): http://stackoverflow.com/questions/10383535/in-ruby-whats-the-relationship-between-new-and-initialize-how-to-return-n – jefflunt Jan 05 '15 at 00:56
1

Ruby automatically calls the initialize method when a new object of that class is created.

new calls the initialize method.

Reference

Community
  • 1
  • 1
B Seven
  • 44,484
  • 66
  • 240
  • 385