info

隙あらばinject、inject小技集

ruby 2.0.0p598

1から10の数を足し合わせた時、途中の状態の数列が欲しい。

(1..10).inject(nil) do |(acc, arr), i| #引数マッチング                          
  next [i, [i]] if arr.nil? #injectの初期化                                     
  [acc + i, arr << acc + i] #次の(acc,arr)に入る                                
end
[55, [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]]

それぞれの要素の間の距離を知りたい

include Math
srand 1145141341893890016
a = (1..10).to_a.shuffle # [5, 3, 4, 7, 6, 10, 2, 8, 9, 1]                      
b = (1..10).to_a.shuffle # [7, 5, 8, 2, 6, 1, 10, 9, 3, 4]                      

a.zip(b).inject(nil) do |((old_x, old_y), arr) ,(x, y)|
  next [[x, y], [0.0]] if arr.nil?
  kyori = sqrt((old_x - x)**2 + (old_y - y)**2)
  [[x, y], arr << kyori]
end
[[1, 4],
 [0.0,
  2.8284271247461903,
  3.1622776601683795,
  6.708203932499369,
  4.123105625617661,
  6.4031242374328485,
  12.041594578792296,
  6.082762530298219,
  6.082762530298219,
  8.06225774829855]]

schemeの引数マッチングを見て思いついた。with_indexの出番が減る、何かスマートなinject初期化方法が欲しい