Ruby/Hash/inject

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

hash inject

require "time"
click_counts = {}
1.upto(30) { |i| click_counts[Time.parse("2006-09-#{i}")] = 400 + rand(700) }
p click_counts
low_click_days_hash = click_counts.inject({}) do |h, kv|
  k, v = kv
  h[k] = v if v < 450
  h
end



inject with regular expression

h = { "apple tree" => "plant", "ficus" => "plant",
      "shrew" => "animal", "plesiosaur" => "animal" }
h.inject([]) { |res, kv| res << kv if kv[1] =~ /p/; res }
p h
# => [["ficus", "plant"], ["apple tree", "plant"]]