Ruby Ruby 中 each.do 集合遍历问题

Cger007 · July 03, 2017 · Last by mlzhuyi replied at July 04, 2017 · 2325 hits

在 ruby 中用 each.do 遍历集合列表的时候,怎么能像 java 中 for(int i=0;i<list.size();i++) 循环那样,知道 i 的值,也就是 each.do 怎么判断正在执行的是第几次

each_with_index do |r, i|

each_with_index , rtfm

hash = Hash.new
%w(cat dog wombat).each_with_index do |item, index|
  hash[item] = index
end
hash   #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
Reply to sec
%w(cat dog wombat).each.with_index.inject({}) do |h, (item, index)|
  h[item] = index
  h
end
%w(cat dog wombat).map.with_index { |iterm, index| [iterm, index] }.to_h
You need to Sign in before reply, if you don't have an account, please Sign up first.