ruby 数组键对值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13364003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:31:16  来源:igfitidea点击:

ruby Array key pair value?

rubyarrayshash

提问by RajG

I am trying to pair up two key value pairs but I am unsure how to accomplish this. Below is what I have attempted:

我正在尝试配对两个键值对,但我不确定如何实现这一点。以下是我尝试过的:

struc = Array[(3,4),(5,6)]
for i in 0..1
    puts "#{struc[i,i]}"
end

But my desired output is the following (which the previous code block does not produce):

但我想要的输出如下(前面的代码块没有产生):

3 4
5 6

回答by Paul Richter

Why not use a hash. With it, you can do:

为什么不使用哈希。有了它,您可以:

struc = {3 => 4, 5 => 6}

To output the result, you can use the each_pair method, like so:

要输出结果,您可以使用 each_pair 方法,如下所示:

struc.each_pair do |key, value|
    puts "#{key} #{value}"
end

回答by simonmenke

try this:

尝试这个:

arr = [[3,4],[5,6]]
arr.each do |(a,b)|
  puts "#{a} #{b}"
end

Also you array syntax (Array[(3,4),(5,6)]) is incorrect.

您的数组语法 ( Array[(3,4),(5,6)]) 也不正确。

回答by Bijan

In Ruby 2.3 you can do the following:

在 Ruby 2.3 中,您可以执行以下操作:

arr = [[3,4],[5,6]]
arr.each do |a,b|
    puts "#{a} #{b}"
end