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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With