# 如何在Ruby循环的第一次迭代中采取不同的行为？

` `i = 0 my_array.each do |item| if i==0 # do something with the first item end # common stuff i += 1 end` `

### 8 Solutions collect form web for “如何在Ruby循环的第一次迭代中采取不同的行为？”

` `my_array.each_with_index do |item, index| if index == 0 # do something with the first item end # common stuff end` `

` `# do something with my_array[0] or my_array.first my_array.each do |e| # do the same general thing to all elements end` `

` `# do something with my_array[0] or my_array.first my_array.drop(1).each do |e| # do the same general thing to all elements except the first end` `

` `my_array.each_with_index do |item, i| item.do_something if i==0 #common stuff end` `

` `# treat the first element (my_array.first) my_array.each do | item | # do the common_stuff end` `

Enumerable中的 `each_with_index` （Enumerable已经和Array混合在一起了，所以你可以在数组上调用它）：

` `irb(main):001:0> nums = (1..10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] irb(main):003:0> nums.each_with_index do |num, idx| irb(main):004:1* if idx == 0 irb(main):005:2> puts "At index #{idx}, the number is #{num}." irb(main):006:2> end irb(main):007:1> end At index 0, the number is 1. => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]` `

` `ar = %w(reversed hello world) puts ar.shift.upcase ar.each{|item| puts item.reverse} #=>REVERSED #=>olleh #=>dlrow` `

Ruby的`Enumerable#inject`提供了一个参数，可以用来在循环的第一次迭代中做不同的事情：

` `> l=[1,2,3,4] => [1, 2, 3, 4] > l.inject(0) {|sum, elem| sum+elem} => 10` `

` `> l.inject {|sum, elem| sum+elem} => 10` `

` `> puts fruits.inject("I like to eat: ") {|acc, elem| acc << elem << " "} I like to eat: apples pears peaches plums oranges => nil` `

` `do_this if (\$first_time_only ||= [true]).shift` `

• Rails检查是否在content_for中定义了yield：area
• Rspec：如何testing文件操作和文件内容
• 什么是耙子，它是如何在轨道中使用的？
• Ruby是否有像堆栈，队列，链接列表，映射或集合的容器？
• 如何在Ruby中获取堆栈跟踪对象？