code_junkie

What is the “right” way to iterate through an array in Ruby?

Nov 12th, 2011
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. foreach (array/hash as $key => $value)
  2.  
  3. array.length.times do |i|
  4. end
  5.  
  6. array.each
  7.  
  8. array.each_index
  9.  
  10. for i in array
  11.  
  12. hash.each do |key, value|
  13.  
  14. array = [1, 2, 3, 4, 5, 6]
  15. array.each { |x| puts x }
  16.  
  17. 1
  18. 2
  19. 3
  20. 4
  21. 5
  22. 6
  23.  
  24. array = ["A", "B", "C"]
  25. array.each_with_index {|x, y| puts "#{x} => #{y}" }
  26.  
  27. A => 0
  28. B => 1
  29. C => 2
  30.  
  31. for index in 0 ... array.size
  32. puts "array[#{index}] = #{array[index].inspect}"
  33. end
  34.  
  35. for key in hash.keys.sort
  36. puts "hash[#{key.inspect}] = #{hash[key].inspect}"
  37. end
  38.  
  39. (1..10).each{|i| puts "i=#{i}" }
  40.  
  41. (1..10).to_a.reverse.each{|i| puts "i=#{i}" }
  42.  
  43. (a=*1..10).each{|i| puts "i=#{i}" }
  44.  
  45. (a=*1..10).reverse.each{|i| puts "i=#{i}" }
  46.  
  47. (*1..10).each{|i| puts "i=#{i}" }
  48. (*1..10).reverse.each{|i| puts "i=#{i}" }
  49. #
  50. (1..10).step(1){|i| puts "i=#{i}" }
  51. (1..10).step(-1){|i| puts "i=#{i}" }
  52. #
  53. (1..10).each{|i| puts "i=#{i}" }
  54. (10..1).each{|i| puts "i=#{i}" } # I don't want this though. It's dangerous
  55.  
  56. class Range
  57.  
  58. def each_reverse(&block)
  59. self.to_a.reverse.each(&block)
  60. end
  61.  
  62. end
  63.  
  64. ary.each_with_index { |val, idx| # ...
  65.  
  66. class Hash
  67. def each_pairwise
  68. self.each { | x, y |
  69. yield [x, y]
  70. }
  71. end
  72. end
  73.  
  74. class Array
  75. def each_pairwise
  76. self.each_with_index { | x, y |
  77. yield [y, x]
  78. }
  79. end
  80. end
  81.  
  82. ["a","b","c"].each_pairwise { |x,y|
  83. puts "#{x} => #{y}"
  84. }
  85.  
  86. {"a" => "Aardvark","b" => "Bogle","c" => "Catastrophe"}.each_pairwise { |x,y|
  87. puts "#{x} => #{y}"
  88. }
  89.  
  90. ['Home', '/', 'Page two', 'two', 'Test', 'test'].each_slice(2) do|label,link|
  91. li {a label, :href => link}
  92. end
  93.  
  94. require 'enumerator'
  95.  
  96. ['a',1,'b',2].to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
  97.  
  98. # is equivalent to...
  99.  
  100. {'a'=>1,'b'=>2}.to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
  101.  
  102. # Ruby 1.8
  103. [1,2,[1,2,3]].flatten
  104. => [1,2,1,2,3]
  105.  
  106. # Ruby 1.9
  107. [1,2,[1,2,3]].flatten(0)
  108. => [1,2,[1,2,3]]
Add Comment
Please, Sign In to add comment