Structs in Ruby are underused. Here are some examples.

This article is quite old.Time flies when you're having fun. I've been writing for my blog for a long time. Stuff changes fast, especially in the Ruby world. That's why I've put this warning on old posts. The article might still be valid, though.

About structs

Recently I talked about a monkey patch called attr_initializer, allowing you to write code like this:

class FooBar
  attr_initializer :foo, :bar
  def to_s
    "your #{foo} is #{bar}"
  end
end

FooBar.new('foo', 'bar')

But there is a way of doing it without a monkey patch. Use the Struct.

FooBar = Struct.new(:foo, :bar) do
  def to_s
    "your #{foo} is #{bar}"
  end
end

FooBar.new('foo', 'bar')

Pretty cool.

Update

As was pointed out in my comments by Radoslav Stankov (which you can't see anymore, because I switched to Disqus), you can also do this:

class FooBar < Struct.new(:foo, :bar)
  def to_s
    "your #{foo} is #{bar}"
  end
end

FooBar.new('foo', 'bar')

I use this one more often, actually.

One final note: the parameters here aren't stored as instance variables, they can only be accessed through their accessor methods.

comments powered byDisqus