Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic object creation in ruby

Tags:

ruby

In ruby, I often find myself writing the following:

class Foo
  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>

end

or even

class Foo
  attr_accessor :bar, :baz

  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>

end

I'm always keen to minimise boilerplate as much as possible - so is there a more idiomatic way of creating objects in ruby?

like image 874
grifaton Avatar asked Nov 22 '09 13:11

grifaton


1 Answers

One option is that you can inherit your class definition from Struct:

class Foo < Struct.new(:bar, :baz)
  # << more stuff >>
end

f = Foo.new("bar value","baz value")
f.bar #=> "bar value"
f.baz #=> "baz value"
like image 62
Raimonds Simanovskis Avatar answered Oct 26 '22 22:10

Raimonds Simanovskis