Ruby - 带索引的数组
我如何在 Ruby 中创建一个带有索引的数组? 我的 PHP 定制是这样的:
@my_array = [0 =>; “一”,3 => “bb”,7 => “CCC”]
我想遍历这个数组 each_with_index 并且我想得到结果,例如形状:
0 - a
3 - bb
7 - ccc
任何人都可以帮助我,怎么办? 谢谢
how can I do in Ruby an array with indexes?
My custom from PHP is something like this:
@my_array = [0 => "a", 3 => "bb", 7 => "ccc"]
And this array I want to go through each_with_index and I would like to get the result, e.g. in a shape:
0 - a
3 - bb
7 - ccc
Can anyone help me, how to do?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们在 ruby 中称为哈希。
参考这里的一堆示例:
Hash
。They're called hashes in ruby.
Reference with a bunch of examples here:
Hash
.你不需要数组,你想要使用哈希。由于您的索引不是连续的(如果使用数组,它们将/应该是连续的),请像这样使用哈希:
现在您可以像这样迭代它:
You don't want an array, you want to use a hash. Since your indices are not sequential (as they would/should be if using an array), use a hash like so:
Now you can iterate through it like this:
ruby 中的数组已经有索引,但如果您想要一个具有您选择的索引的关联数组,请使用哈希:
Arrays in ruby already have indexes but if you want an associative array with index of your choice, use a Hash: