spicyShoyo spicyShoyo - 2 months ago 9
Ruby Question

Ruby class variable example

I am trying to translate the below Python code to Ruby. I would like to access "a" and change it in the future.

class c:
def __init__(self, a):
self.a = a

o = new c(2)
print(o.a)


I read about instance variables of Ruby, but the tutorials are very long and confusing.
I have tried:

class C
def initialize(a)
@a = a
end
end
o = C.new(2)
puts o.a


but it just doesn't work.
I end up with this:

class C
def initialize(a)
@a = a
def a
@a
end
end
end


but this one is just too stupid.

Can someone please just translate above Python code correctly to Ruby? Thank you!

Answer

Try to use the ruby convention of capitalizing the class names. It makes the code more readable.

The instance variables are only accessible in the body of the class, if you want to access them you have to write a method that returns their value

class MyClass
    def initialize(a)
        @a = a
    end

    def get_a
        @a
    end
end

x = MyClass(7)
puts x.get_a

If you want to set the instance variable

class MyClass
    ...
    def set_a(a)
        @a = a
    end
end

x = MyClass(7)
x.set_a(6)

you can use properties for this

class MyClass
    ...
    def a=(a)
        @a = a
    end
end

x = MyClass(7)
x.a = 9

ruby has shortcuts for these use cases called accessors:

 attr_reader :v     def v; @v; end
 attr_writer :v     def v=(value); @v=value; end
 attr_accessor :v   attr_reader :v; attr_writer :v
 attr_accessor :v, :w   attr_accessor :v; attr_accessor :w

see Why use Ruby's attr_accessor, attr_reader and attr_writer?