P
Paul Jungwirth
Hello,
I have a question about ruby's feature that when you call a method, you
can pass in a block of code after the last argument. Instead of writing
a code block, suppose I already have a def'd method that would work just
as well. Is there any way I can pass that in directly? For example,
suppose I have this code:
#!/usr/bin/env ruby
def fib(n)
a, b = 0, 1
n.times do |i|
a, b = b, a+b
end
b
end
c = [1, 2, 3, 4]
puts c.collect {|i| fib i}
That will print fib(1), fib(2), fib(3), fib(4). But why write a code
block that takes one argument and does nothing but call a function that
takes one argument? Is there some way I could have replaced the last
line with something like this?:
puts c.collect \fib
In python I could have written the last line thus:
print map(fib, (1, 2, 3, 4))
Does ruby have something similar?
Thanks,
Paul
I have a question about ruby's feature that when you call a method, you
can pass in a block of code after the last argument. Instead of writing
a code block, suppose I already have a def'd method that would work just
as well. Is there any way I can pass that in directly? For example,
suppose I have this code:
#!/usr/bin/env ruby
def fib(n)
a, b = 0, 1
n.times do |i|
a, b = b, a+b
end
b
end
c = [1, 2, 3, 4]
puts c.collect {|i| fib i}
That will print fib(1), fib(2), fib(3), fib(4). But why write a code
block that takes one argument and does nothing but call a function that
takes one argument? Is there some way I could have replaced the last
line with something like this?:
puts c.collect \fib
In python I could have written the last line thus:
print map(fib, (1, 2, 3, 4))
Does ruby have something similar?
Thanks,
Paul