简体   繁体   English

Ruby中的哈希/对象数组

[英]Hash/Array of objects in Ruby

I'm pretty new to Ruby (I come from a C++ background) and I have an array/hash of objects by their name but I'm having no luck when trying to access their variables. 我是Ruby的新手(我来自C ++背景),并且按对象名称有对象的数组/哈希值,但是尝试访问它们的变量时我没有运气。 This is my attempt: 这是我的尝试:

class Foo
attr_reader :num

def initialize(num)
    @num = num
end
end

foo_list = {}

foo_list["one"] = Foo.new("124")
foo_list["two"] = Foo.new("567")

foo_list.each do |foo|
p "#{foo.num}"              # ERROR: undefined method 'num'
end

I'm pretty sure there is an easy way of doing what I need, maybe not even using 'each' but something else? 我敢肯定,有一种简单的方法可以做我需要的事情,也许甚至不使用“每个”,而是其他?

You might be looking for this: 您可能正在寻找:

foo_list.each do |key, value|
  puts "#{key}: #{value}"
end

Or you can extend your own example (foo would be an array here containing the key and value): 或者,您可以扩展自己的示例(foo将是一个包含键和值的数组):

foo_list.each do |foo|
  puts "#{foo[0]}: #{foo[1]}"
end

Or you could do this without the each: 或者,您可以在没有每个方法的情况下执行此操作:

puts "one: #{foo_list["one"]}"
puts "two: #{foo_list["two"]}"

Have fun learning Ruby! 玩得开心学习Ruby! :-) :-)

Shouldn't that be foo_list.each do |key, foo| 那不应该是foo_list.each do |key, foo| , given that foo_list is a hash? ,因为foo_list是哈希?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM