Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Feb 7 ’12

Initialize Objects with a Hash

If you want to initialize new instances of your class and specify values for its attributes directly, you can implement an initialize method with a lot of arguments. Or you can use a Hash - the Rails way:

my_puppy = Dog.new(:name => "Luke", :birthdate => Time.now)

You can do this by using a general initialize implementation:

module GeneralInit
  def initialize(*h)
    if h.length == 1 && h.first.kind_of?(Hash)
      h.first.each { |k,v| send("#{k}=",v) }
    end
  end
end

For every class that needs to take advantage of this, you just have to include GeneralInit. The initialize method will be available and work the way you expect it to.
It is still possible to create a new instance without arguments (Dog.new), or passing in a Hash with attribute/value pairs (as shown in the example above).

This tip was submitted by Rik Vanmechelen.

6 notes 0 comments

  1. aberezovsky reblogged this from rubyquicktips and added:
    Also keep in mind...skip {} and object could looks like my_shiny_object
  2. susatadahiro reblogged this from rubyquicktips
  3. Rik Vanmechelen submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus