Ruby中的基本数组迭代

前端之家收集整理的这篇文章主要介绍了Ruby中的基本数组迭代前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在迭代另一个数组时遍历数组的更好方法是什么?例如,如果我有两个如下所示的数组:
  1. names = [ "Rover","Fido","Lassie","Calypso"]
  2. breeds = [ "Terrier","Lhasa Apso","Collie","Bulldog"]

假设阵列彼此对应 – 也就是说,Rover是一个Terrier,Fido是Lhasa Apso等等 – 我想创建一个狗类,并为每个项目创建一个新的狗对象:

  1. class Dog
  2. attr_reader :name,:breed
  3.  
  4. def initialize(name,breed)
  5. @name = name
  6. @breed = breed
  7. end
  8. end

我可以通过以下方式遍历名称和品种:

  1. index = 0
  2.  
  3. names.each do |name|
  4. Dog.new("#{name}","#{breeds[index]}")
  5. index = index.next
  6. end

但是,我觉得使用索引变量是错误方法.什么是更好的方式?

解决方法

  1. dogs = names.zip(breeds).map { |name,breed| Dog.new(name,breed) }

Array#zip使用参数的元素交换目标数组,所以

  1. irb> [1,2,3].zip(['a','b','c'])
  2. #=> [ [1,'a'],[2,'b'],[3,'c'] ]

您可以使用不同长度的数组(在这种情况下,目标数组确定结果数组的长度,并使用nil填充额外的条目).

  1. irb> [1,3,4,5].zip(['a','c'],[4,nil],[5,nil] ]
  2. irb> [1,'c','d','e'])
  3. #=> [ [1,'c'] ]

您还可以将两个以上的阵列压缩在一起:

  1. irb> [1,[:alpha,:beta,:gamma])
  2. #=> [ [1,'a',:alpha],:beta],:gamma] ]

Array#map是一种转换数组的好方法,因为它返回一个数组,其中每个条目都是在目标数组中相应条目上运行块的结果.

  1. irb> [1,3].map { |n| 10 - n }
  2. #=> [ 9,8,7 ]

在数组数组上使用迭代器时,如果给出一个多参数块,则数组条目将自动分解为这些参数:

  1. irb> [ [1,'c'] ].each { |array| p array }
  2. [ 1,'a' ]
  3. [ 2,'b' ]
  4. [ 3,'c' ]
  5. #=> nil
  6. irb> [ [1,'c'] ].each do |num,char|
  7. ...> puts "number: #{num},character: #{char}"
  8. ...> end
  9. number 1,character: a
  10. number 2,character: b
  11. number 3,character: c
  12. #=> [ [1,'c'] ]

Matt Briggs mentioned一样,#each_with_index是另一个了解的好工具.它遍历数组的元素,依次传递每个元素的块.

  1. irb> ['a','c'].each_with_index do |char,index|
  2. ...> puts "character #{char} at index #{index}"
  3. ...> end
  4. character a at index 0
  5. character b at index 1
  6. character c at index 2
  7. #=> [ 'a','c' ]

使用像#each_with_index这样的迭代器时,可以使用括号将数组元素分解为其组成部分:

  1. irb> [ [1,'c'] ].each_with_index do |(num,char),index|
  2. ...> puts "number: #{num},character: #{char} at index #{index}"
  3. ...> end
  4. number 1,character: a at index 0
  5. number 2,character: b at index 1
  6. number 3,character: c at index 2
  7. #=> [ [1,'c'] ]

猜你在找的Ruby相关文章