In Ruby, is there a way to "arr.sort {|i| Math.cos(i)*Math.sin(i)}" instead using |i,j| and repeat it twice?

nop*_*ole 1 ruby

Such as the code:

irb(main):001:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]

irb(main):002:0> a.sort {|d,e| (d - 3).abs <=> (e - 3).abs}
=> [3, 2, 4, 1, 5]    # sort by closest distance away from the number 3
Run Code Online (Sandbox Code Playgroud)

it is not so good to repeat the expression twice, and it is too trivial to create a function just for that expression. Is there also a way to write something like

irb(main):002:0> a.sort {|e| (e - 3).abs}  # compare by this expression
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 8

你正在寻找sort_by方法:

a.sort_by {|e| (e - 3).abs}
Run Code Online (Sandbox Code Playgroud)