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)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |