开发者

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

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 th开发者_如何转开发e number 3

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


You're looking for the sort_by method:

a.sort_by {|e| (e - 3).abs}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜