4 ms·
I implemented these examples in Ruby 1.9, would love to know if there are more efficient ways of doing some of these: def cook(p1, p2, f) puts "get t
by ericf 15y ago
I implemented these examples in Ruby 1.9, would love to know if there are more efficient ways of doing some of these:
def cook(p1, p2, f)
puts "get the " + p1.to_s
f.call(p1)
f.call(p2)
end
cook( "lobster", "water", lambda {|x| puts "pot " + x })
cook( "chicken", "coconut", lambda {|x| puts "boom " + x })
@a = [1,2,3]
@a.map {|x| puts x*2}
@a.map {|x| puts x}
def sum(a)
@a.reduce(0) do |a, b|
a + b
end
end
def join(a)
@a.reduce("") do |a, b|
a.to_s + b.to_s
end
end
puts "sum " + sum(@a).to_s
puts "join " + join(@a)
- flatwhatson 15y agoHere's one more efficient way... use perl! #!/usr/bin/perl use Modern::Perl; use List::Util 'reduce'; sub cook { my ($i1, $i2, $f) = @_; say "get the $i1"; $f->($i1); $f->($i2); } cook "lobster", "water", sub { say "pot " . shift }; cook "chicken", "coconut", sub { say "boom " . shift }; my @a = (1, 2, 3); map { say $_ * 2 } @a; map { say $_ } @a; sub my_sum { reduce { $a + $b } 0, @_; } sub my_join { reduce { $a . $b } "", @_; } say "sum " . my_sum(@a); say "join " . my_join(@a);