0

What I can't understand is the

def initialize(awesome_level2) @awesome_level2 = awesome_level2

Does the @awesome_level2 have to have the same name as awesome_level2?

It seems if I change it, it doesn't work properly

class Awesome
        attr_accessor :awesome_level2
    def initialize(awesome_level2)
        p awesome_level2 #100
        @awesome_level2 = awesome_level2
        P @awesome_level2 #100
    end 
end

awesome_sauce = awesome.new(100)
puts awesome_sauce.awesome_level2  #100 where is awesome_level2 from?
awesome_sauce.awesome_level = 99
puts awesome_sauce.awesome_level   #99
  • What do those puts output? What are you expecting? I think you have an extra capitalized A in that initialize method – Prescott Apr 26 '15 at 05:23

1 Answers1

0

attr_accessor is a convenience method that creates getter and setter methods for the symbols you pass as arguments. You can then access the instance variable it creates directly, in this case @awesome_level2. Note that this has the @ symbol in front of it, which indicates it's an instance variable. This is different from a local variable or a method parameter which does not have the @ sign. Therefore in your initialize method, the variable names @awesome_list2 and awesome_list2 are different and can hold different values.

As @Prescott has said, it seems as though you were trying to set your instance variable @awesome_list2 to the argument passed to your initializer, awesome_list2, but accidentally wrote it with a capital A, which is just going to set it to nil since an object with the name Awesome_list2 (note the capital 'A') doesn't exist (I presume).

Rob Wise
  • 4,930
  • 3
  • 26
  • 31
  • The "A" was put in when I typed up the question it was not in my code when i tried it. Can i name the @awesome_level2 different than awesome_level2? Or is it the same because its an instance level. – Stacy Proficy Apr 26 '15 at 05:38
  • I think i get it because i have attr_accessor = awesome_level2. I have to call it @aweome_level2. I think those two have to be the same. Is that right? – Stacy Proficy Apr 26 '15 at 06:04
  • @StacyProficy yes, that is correct. Calling `attr_accessor :foobar` will create the getter and setter methods as well as an instance variable called `@foobar`. Perhaps [this popular SO thread](http://stackoverflow.com/a/4371458/3259320) explaining `attr_accessor` will help clarify things? – Rob Wise Apr 26 '15 at 16:37
  • Thank you all that was perfect... Cheers – Stacy Proficy Apr 26 '15 at 22:33
  • No problem! If you feel that your question has been adequately answered, upvote it and accept it so that others can find it and know that it has been answered. – Rob Wise Apr 26 '15 at 22:59