Wednesday, December 13, 2006

Ruby - Default Values for Method Arguments

>> def test(args)
>  >>   puts args.values_at(:a, :b, :c)
>  >> end
> => nil
>  >> test :a => 1, :c => 2

def test(args)
>>   args = { "a" => "default a",
?>            "b" => "default b",
?>            "c" => "default c" }.merge(args)
>>   puts args.values_at("a", "b", "c")
>> end
=> nil
>> test "a" => "some a", "c" => "some c"
some a
default b
some c
=> nil
Source :
def test(args)
  args[:a] ||= 'defaultA'
  args[:b] ||= 'defaultB'
  args[:c] ||= 'defaultC'
  puts args.indexes(:a, :b, :c)
end
Result: Breaks when...
test :a => false
test :a => nil
test 'a' => true

No comments: