Daniel Schüle
1/9/2006 3:45:00 PM
Hello all,
I am looking for Ruby equivalent for this Python Code
>>> def foo(a,b,c):
.... print "a is ", a
.... print "b is ", b
.... print "c is ", c
....
>>> h = {"c":3, "a":1, "b":2}
>>>
>>> foo
<function foo at 0x403d6f7c>
>>> foo(**h)
a is 1
b is 2
c is 3
my first try
=> {"c"=>333, :b=>2, :a=>1}
irb(main):017:0> def foo a,b,c
irb(main):018:1> puts "a is #{a}"
irb(main):019:1> puts "b is #{b}"
irb(main):020:1> puts "c is #{c}"
irb(main):021:1> end
=> nil
irb(main):022:0> foo *h
a is c333
b is b2
c is a1
=> nil
this seem to replace (or substituate) the parameters expected by foo
in the order of hash. And since hash has no order (in both languages)
it's a random replacement.
Is there a trick I don't know about?
Regards, Daniel
ps:
The case of unpacking an array seem to be 1:1 mapping betweeen Python
and Ruby.
>>> n = [1,2,3]
>>>
>>> def bar(*args):
.... for i in args:
.... print i
....
>>> bar(*n)
1
2
3
>>>
>>> bar(1,2,3)
1
2
3
>>>
irb(main):065:0> def bar *args
irb(main):066:1> args.each {|i| puts i}
irb(main):067:1> end
=> nil
irb(main):068:0> n = [1,2,3]
=> [1, 2, 3]
irb(main):069:0> bar(*n)
1
2
3
=> [1, 2, 3]
irb(main):070:0> bar(1,2,3)
1
2
3
=> [1, 2, 3]
irb(main):071:0>