什么是“权利"?在 Ruby 中遍历数组的方法? [英] What is the "right" way to iterate through an array in Ruby?

查看:24
本文介绍了什么是“权利"?在 Ruby 中遍历数组的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP,尽管有缺点,但在这一点上还是不错的.数组和散列之间没有区别(也许我很天真,但这对我来说显然是正确的),并且要遍历其中任何一个,您只需执行

PHP, for all its warts, is pretty good on this count. There's no difference between an array and a hash (maybe I'm naive, but this seems obviously right to me), and to iterate through either you just do

foreach (array/hash as $key => $value)

在 Ruby 中有很多方法可以做这种事情:

In Ruby there are a bunch of ways to do this sort of thing:

array.length.times do |i|
end

array.each

array.each_index

for i in array

哈希更有意义,因为我总是使用

Hashes make more sense, since I just always use

hash.each do |key, value|

为什么我不能对数组执行此操作?如果我只想记住一种方法,我想我可以使用 each_index(因为它使索引和值都可用),但是不得不做 array[index] 而不仅仅是 value.

Why can't I do this for arrays? If I want to remember just one method, I guess I can use each_index (since it makes both the index and value available), but it's annoying to have to do array[index] instead of just value.

哦,对了,我忘记了 array.each_with_index.然而,这个很糟糕,因为它是 |value, key|hash.each|key, value|!这不是疯了吗?

Oh right, I forgot about array.each_with_index. However, this one sucks because it goes |value, key| and hash.each goes |key, value|! Is this not insane?

推荐答案

这将遍历所有元素:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

打印:

1
2
3
4
5
6

这将遍历所有为您提供值和索引的元素:

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

打印:

A => 0
B => 1
C => 2

从你的问题中我不太确定你要找哪一个.

I'm not quite sure from your question which one you are looking for.

这篇关于什么是“权利"?在 Ruby 中遍历数组的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆