Created
October 21, 2011 19:38
-
-
Save bkempner/1304733 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
def initialize(options) | |
@bar = options.fetch(:bar, nil) | |
@baz = options.fetch(:baz, nil) | |
end | |
end | |
def Foo(options) | |
Foo.new(options) | |
end | |
ruby-1.9.2-p290 :028 > f = Foo bar: 'chuck', baz: 'testa' | |
=> #<Foo:0x007ffdd407fec0 @foo="chuck", @bar="testa"> |
Ahhh. That's an important catch. Cool!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sashah87
Also, with a condition you could have problems if the value of options[:foo] is false, then it will always set default value. With fetch it will only set default value if the key is missing.
Also, another trick I just learned:
h = Hash.new { 'foo' }
h[:foo] #=> 'foo'
h[:bar] #=> 'foo'
h[:baz] = 'baz' #=> 'baz'