Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: shorter way to define instance variables

Tags:

ruby

ruby-2.1

I'm looking for the shorter way to define instance variables inside the initialize method:

class MyClass
  attr_accessor :foo, :bar, :baz, :qux
  # Typing same stuff all the time is boring
  def initialize(foo, bar, baz, qux)
    @foo, @bar, @baz, @qux = foo, bar, baz, qux
  end
end

Does Ruby have any in-build feature which lets to avoid this kind of monkey job?

# e. g.
class MyClass
  attr_accessor :foo, :bar, :baz, :qux
  # Typing same stuff all the time is boring
  def initialize(foo, bar, baz, qux)
    # Leveraging built-in language feature
    # instance variables are defined automatically
  end
end
like image 381
DreamWalker Avatar asked Mar 05 '26 11:03

DreamWalker


1 Answers

Meet Struct, a tool made just for this!

MyClass = Struct.new(:foo, :bar, :baz, :qux) do
  # Define your other methods here. 
  # Initializer/accessors will be generated for you.
end

mc = MyClass.new(1)
mc.foo # => 1
mc.bar # => nil

I often see people use Struct like this:

class MyStruct < Struct.new(:foo, :bar, :baz, :qux)
end

But this results in one additional unused class object. Why create garbage when you don't need to?

like image 141
Sergio Tulentsev Avatar answered Mar 07 '26 23:03

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!