-2

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!

spicyShoyo
  • 343
  • 1
  • 7
  • 13
  • Your question is confusing. You ask about class variables, but there aren't any class variables in either the Python or the Ruby example. – Jörg W Mittag Sep 24 '16 at 23:14

1 Answers1

2

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

Please note that this solution is discouraged and you should use attr_reader or attr_accessor instead.

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?

Community
  • 1
  • 1
Pablo
  • 13,271
  • 4
  • 39
  • 59
  • Going down the `get_a` road is a little misleading. `attr_accessor` is the correct answer as you note later on, but that's really the first thing to mention. – tadman Sep 25 '16 at 01:32