Steve Dogers wrote:
Hi, I have a couple questions about instance variables in Ruby.
1) do i need to declare them at the top of my class file - I do
understand the accessors are automatic
Then you're understanding is faulty:
class Person
def initialize(name, age)
@name = name
@age = age
end
end
p = Person.new("Steve", 25)
puts p.name
--output:--
undefined method `name' for #<Person:0x2529c @age=25, @name="Steve">
(NoMethodError)
but I'm not sure if I can just
pull a @product in the middle of a function
They are called "methods" in ruby.
class Person
def initialize(name, age)
@name = name
@age = age
end
def somefunc(x)
@product = x
end
def show
puts "I have #{@product}"
end
end
p = Person.new("Steve", 25)
p.somefunc("Shoes")
p.show
--output:--
I have Shoes
2) do i need to use the @ to refer to them in the class. Would it work
without the @,
class Person
def initialize(name, age)
@name = name
@age = age
end
def somefunc(x)
@product = x
end
def show
puts "I have #{product}" #<-- no @
end
end
p = Person.new("Steve", 25)
p.somefunc("Shoes")
p.show
--output:--
in show undefined local variable or method `product' for
#<Person:0x24ef0 @age=25, @product="Shoes", @name="Steve"> (NameError)
and if so, how does it differentiate them from local
vars?
class Person
def initialize(name, age)
@name = name
@age = age
end
def somefunc(x)
@product = x
end
def show
product = "Sandals"
puts "I have #{product}"
puts "I have #{@product}"
end
end
p = Person.new("Steve", 25)
p.somefunc("Shoes")
p.show
--output:--
I have Sandals
I have Shoes
3) I've seen code where just below the class declaration, objects are
instantiated like product = Product.new - I don't see a @ sign, does
that mean it's a local var? How can a local var even exist at the class
level, outside a function?
class Product
def initialize
@product = "Shoes"
end
end
class Person
product = Product.new
def initialize(name, age)
@name = name
@age = age
end
def show
#puts product
#puts @product
#puts @@product
puts Person.product
end
end
p = Person.new("Steve", 25)
p.show
--output:--
in `show': undefined method `product' for Person:Class (NoMethodError)
from r3test.rb:24
···
--
Posted via http://www.ruby-forum.com/\.