About class variable question?

Z

Zhao Yi

Please see this code below. It will get "can't convert nil to string
error". Why can't the @name be assigned? I have set the @name = "world".

class Hello
@name="world"
def say
puts "Hello "+@name
end
end
h=Hello.new
h.say
 
S

Stefano Crocco

Please see this code below. It will get "can't convert nil to string
error". Why can't the @name be assigned? I have set the @name = "world".

class Hello
@name="world"
def say
puts "Hello "+@name
end
end
h=Hello.new
h.say

@name is an instance variable of the Hello object, not of instances of Hello,
such as h. To create an instance variable of instances of Hello, you need to
assign it a value in an instance method. Usually, this is done in the
initialize method:

class Hello

def initialize
@name = "Hello"
end

def say
puts "Hello" + @name
end

end

h = Hello.new
h.say

I hope this helps

Stefano
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top