Adventures with Ruby

About structs

View Comments

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.

Written by Iain Hecker

June 28th, 2010 at 9:51 am

Posted in iain.nl

  • http://vanbergen.org Willem van Bergen

    Whoops, read your article wrong :-)

  • http://vanbergen.org Willem van Bergen

    Whoops, read your article wrong :-)

  • http://rstankov.com Radoslav Stankov

    Struct is very underrated (in my opinion) feature in Ruby.

    But I prefer todo just:

    class FooBar < Struct.new(:foo, :bar)
    end

  • http://rstankov.com Radoslav Stankov

    Struct is very underrated (in my opinion) feature in Ruby.

    But I prefer todo just:

    class FooBar < Struct.new(:foo, :bar)
    end

  • http://iain.nl Iain Hecker

    Most of the times, I do that too.

  • http://iain.nl Iain Hecker

    Most of the times, I do that too.

blog comments powered by Disqus
Fork me on GitHub