如何在Ruby中创建哈希数组

时间:2021-05-10 16:01:10

New to ruby and I'm trying to create an array of hashes (or do I have it backwards?)

红宝石的新手,我正在尝试创建一个哈希数组(或者我是否向后?)

def collection
  hash = { "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }
  array = []
  array.push(hash)
  @collection = array[0][:firstname]
end

@collection does not show the firstname for the object in position 0... What am I doing wrong?

@collection没有显示位置0中对象的名字...我做错了什么?

Thanks in advance!

提前致谢!

3 个解决方案

#1


44  

You're using a Symbol as the index into the Hash object that uses String objects as keys, so simply do this:

您正在使用Symbol作为使用String对象作为键的Hash对象的索引,因此只需执行以下操作:

@collection = array[0]["firstname"]

I would encourage you to use Symbols as Hash keys rather than Strings because Symbols are cached, and therefore more efficient, so this would be a better solution:

我鼓励你使用Symbols作为Hash键而不是字符串,因为符号被缓存,因此效率更高,所以这将是一个更好的解决方案:

def collection
  hash = { :firstname => "Mark", :lastname => "Martin", :age => 24, :gender => "M" }
  array = []
  array.push(hash)
  @collection = array[0][:firstname]
end

#2


2  

You have defined the keys of your hash as String. But then you are trying to reference it as Symbol. That won't work that way.

您已将哈希的键定义为String。但是你试图将它作为符号引用。这不会那样。

Try

尝试

@collection = array[0]["firstname"]

#3


1  

You can do this:

你可以这样做:

@collection = [{ "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }]

#1


44  

You're using a Symbol as the index into the Hash object that uses String objects as keys, so simply do this:

您正在使用Symbol作为使用String对象作为键的Hash对象的索引,因此只需执行以下操作:

@collection = array[0]["firstname"]

I would encourage you to use Symbols as Hash keys rather than Strings because Symbols are cached, and therefore more efficient, so this would be a better solution:

我鼓励你使用Symbols作为Hash键而不是字符串,因为符号被缓存,因此效率更高,所以这将是一个更好的解决方案:

def collection
  hash = { :firstname => "Mark", :lastname => "Martin", :age => 24, :gender => "M" }
  array = []
  array.push(hash)
  @collection = array[0][:firstname]
end

#2


2  

You have defined the keys of your hash as String. But then you are trying to reference it as Symbol. That won't work that way.

您已将哈希的键定义为String。但是你试图将它作为符号引用。这不会那样。

Try

尝试

@collection = array[0]["firstname"]

#3


1  

You can do this:

你可以这样做:

@collection = [{ "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }]