Consider the following sample ruby class
class User
def hello
puts \"hello\"
end
end
now, for initialization. there are two ways
<
A normal variable has scope only within the current context; an instance variable has scope throughout one instance of a class. In your case they're confused because the context is main
, which acts as an instance of Object
.
Consider the following, which may make things clearer
class User
def set_name
@name = "Bob"
surname = "Cratchett"
end
def hi
puts "Hello, " + @name
end
def hello
puts "Hello, Mr " + surname
end
end
irb(main):022:0> u = User.new
=> #
irb(main):023:0> u.set_name
irb(main):024:0> u.hi
Hello, Bob
=> nil
irb(main):025:0> u.hello
NameError: undefined local variable or method `surname' for #