ruby hash params = [] params<< {:param => :testString,type :: string}

时间:2014-01-24 06:48:32

标签: ruby arrays hash types

我遇到过这段代码,无法理解它实际上是做什么的。你能解释一下这是做什么的:

params = [] 
params << {:param => :testString, type : :string}
params << {:param => :testJson, type : :string}

3 个答案:

答案 0 :(得分:1)

Array#<<方法将一个项追加到数组的末尾。

a = []
a << 1
a << 2
a # => [1, 2]

因此代码将两个哈希对象添加到params数组。

BTW,您的哈希文字会导致语法错误。删除type:之间的空格。

params << {:param => :testString, type : :string}
#                                     ^

答案 1 :(得分:0)

正确的代码是(您的代码中存在语法错误):

params << {:param => :testString, type: :string}
# => [{:param=>:testString, :type=>:string}] 
params << {:param => :testJson, type: :string}
# => [{:param=>:testString, :type=>:string}, {:param=>:testJson, :type=>:string}] 

代码只会将您定义的Hash添加到Array中。方法<<会将指定的值附加到Array的末尾,并且不会验证该值是否已存在于Array中。

请不要混合旧版本的哈希对(使用=>)和新版本(使用:),因为它的视图非常奇怪。所以:

params << {:param => :testString, type => :string}

params << {param: :testString, type: :string}

答案 2 :(得分:0)

以下是<<(推送)方法的详细信息。

params = [] #instantiate new array named params
params << {:param => :testString, type: :string} #uses the << method to push a hash into the params array
params << {:param => :testJson, type: :string} #uses the << method to push a hash into the params array

params数组的内容现在将是

[{:param => :testString, type: :string},{:param => :testJson, type: :string}]