Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegantly implementing 'map (+1) list' in ruby

Tags:

ruby

The short code in title is in Haskell, it does things like

list.map {|x| x + 1}

in ruby.

While I know that manner, but what I want to know is, is there any more elegant manners to implement same thing in ruby like in Haskell.

I really love the to_proc shortcut in ruby, like this form:

[1,2,3,4].map(&:to_s)
[1,2,3,4].inject(&:+)

But this only accept exactly matching argument number between the Proc's and method.

I'm trying to seek a way that allow passing one or more arguments extra into the Proc, and without using an useless temporary block/variable like what the first demonstration does.

I want to do like this:

[1,2,3,4].map(&:+(1))

Does ruby have similar manners to do this?

like image 226
Shou Ya Avatar asked May 25 '12 19:05

Shou Ya


2 Answers

Use the ampex gem, which lets you use methods of X to build up any proc one one variable. Here’s an example from its spec:

["a", "b", "c"].map(&X * 2).should == ["aa", "bb", "cc"]
like image 25
Josh Lee Avatar answered Sep 25 '22 09:09

Josh Lee


If you just want to add one then you can use the succ method:

>> [1,2,3,4].map(&:succ)
=> [2, 3, 4, 5]

If you wanted to add two, you could use a lambda:

>> add_2 = ->(i) { i + 2 }
>> [1,2,3,4].map(&add_2)
=> [3, 4, 5, 6]

For arbitrary values, you could use a lambda that builds lambdas:

>> add_n = ->(n) { ->(i) { i + n } }
>> [1,2,3,4].map(&add_n[3])
=> [4, 5, 6, 7]

You could also use a lambda generating method:

>> def add_n(n) ->(i) { i + n } end
>> [1,2,3,4].map(&add_n(3))
=> [4, 5, 6, 7]
like image 99
mu is too short Avatar answered Sep 22 '22 09:09

mu is too short