Skip to content

Instantly share code, notes, and snippets.

@coffeencoke
Created January 11, 2012 22:26
Show Gist options
  • Save coffeencoke/1597151 to your computer and use it in GitHub Desktop.
Save coffeencoke/1597151 to your computer and use it in GitHub Desktop.
How to? default hash paramater being given as nil
class Something
def initialize(hash={})
hash ||= {} # Do not want to do this!
@my_attribute = hash[:my_attribute]
end
end
Something.new(nil) # nil param happens with forms occasionally
Something.new({})
Something.new(:my_attribute => 'something')
@coffeencoke
Copy link
Author

How to eliminate line 3?

@davetron5000
Copy link

make Hash, an analog of the handy Array

module Kernel
  def Hash(possible_hash); possible_hash || {}; end
end

class Something
  def initialize(hash={})
    @my_attribute = Hash(hash)[:my_attribute]
  end
end

Something.new(nil) # nil param happens with forms occasionally
Something.new({})
Something.new(:my_attribute => 'something')

Or use OpenStruct

class Something
  def initialize(hash={})
    @my_attribute = OpenStruct.new(hash).my_attribute
  end
end

Something.new(nil) # nil param happens with forms occasionally
Something.new({})
Something.new(:my_attribute => 'something')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment