0

Can someone please help me understand why the class attribute is losing the value outside the initialize method?

2.0.0-p0 :031 > $arr = [1, 2, 3, 4]
 => [1, 2, 3, 4] 
2.0.0-p0 :032 > class Class1
2.0.0-p0 :033?>   def initialize
2.0.0-p0 :034?>     val1 = $arr[0]
2.0.0-p0 :035?>     puts val1
2.0.0-p0 :036?>     end 
2.0.0-p0 :037?>   end 
=> nil 
2.0.0-p0 :038 > cl1 = Class1.new
1   
=> #<Class1:0x007fe8ac16be70> 
2.0.0-p0 :039 > puts cl1.val1

=> nil 
2.0.0-p0 :040 > 

3 Answers 3

5

In a lot of programming languages, including Ruby, variables are scoped, and in your code val1 is in the local scope. It is forgotten when the scope – in this case the function – ends. You probably wanted an instance variable.

A local variable has a name starting with a lower case letter or an underscore character (_).

Each object represents its own song, so we need each of our Song objects to carry around its own song name, artist, and duration. This means we need to store these values as instance variables within the object. In Ruby, an instance variable is simply a name preceded by an at sign (@).

One you have an instance variable, you can access it.

class Person
  def name
    @name # simply returning an instance variable @name
  end
end

person = Person.new
person.name # => nil

But you won't be able to set a value:

person.name = "miku" # => no method error

So for read and write access you'll need provide writer methods or use attr_accessor. This answer explains it in examples: What is attr_accessor in Ruby?

Refs:

1
  • I had val1 as a member variable. But was trying to reopen a class and add functionality to it. That was a good catch. I think the issue was because of the missing @.
    – Karthick S
    May 23, 2013 at 10:19
2

Continuing from @miku's answer you need to define var1 as instance variable to be able to be accessed outside of initialize

irb(main):013:0> class Class1
irb(main):014:1>   attr_accessor :val1
irb(main):015:1>   def initialize
irb(main):016:2>     @val1 = $arr[0]
irb(main):017:2>     puts @val1
irb(main):018:2>     end
irb(main):019:1>   end
=> nil
irb(main):020:0> c = Class1.new
1
=> #<Class1:0x8016f79e0 @val1=1>
irb(main):021:0> puts c.val1
1
=> nil
2

Probably what you are trying to do is:

class Class1
  def initialize
    @val1 = $arr[0]
    puts @val1
  end 
end

Although maybe it would be better to pass the value you want to initialize in the constructor's argument:

class Class1
  def initialize(val)
    @val1 = val
    puts @val1
  end 
end

cl1=Class1.new($arr[0])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.