Jason Baker
Jason Baker

Reputation: 198707

What is the idiomatic way to set class/instance variables in a class definition in Ruby?

For instance, in Python, I can create a class like this:

class foo(object):
    bar = 'x'
    def __init__(self, some_value):
        self.some_attr = some_value

...where bar is a class attribute and some_attr is an instance attribute. What is the idiomatic way to do things like this in Ruby?

Upvotes: 1

Views: 165

Answers (2)

Johan
Johan

Reputation: 1302

Pretty much what weppos wrote, but I would use the @-sigil for the instance variable (it's common practice).

Like:

def initialize(some_value)
    @some_attr = some_value
end

Also, I would not name the class "Foo", but that has nothing do to with Ruby.

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176472

class Foo

  @@bar = 'x'
  attr_accessor :some_attr

  def initialize(some_value)
    self.some_attr = some_value
  end

end

Upvotes: 6

Related Questions