ruby hash params = [] params << {:param =>:testString,type :: string}
问题描述:
我碰到过这段代码,无法理解它实际做了什么。你能解释一下我这是什么呢:ruby hash params = [] params << {:param =>:testString,type :: string}
params = []
params << {:param => :testString, type : :string}
params << {:param => :testJson, type : :string}
答
正确的代码(你必须在你的代码的语法错误):
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}
答
的Array#<<
方法追加一个项目到所述阵列的端部。
a = []
a << 1
a << 2
a # => [1, 2]
因此,该代码将两个散列对象添加到params
阵列。
顺便说一句,你的哈希文字会导致语法错误。删除type
和:
之间的空格。
params << {:param => :testString, type : :string}
# ^
答
以下是关于<<(Push)方法的详细信息。
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
参数数组的内容现在将
[{:param => :testString, type: :string},{:param => :testJson, type: :string}]
谢谢Majioa,作为代码之前粘贴,因此,这是相同PARAMS = [] PARAMS :的TestString,:类型=>:字符串} params :testJson,:type =>:string} – Swamy
@Swamy在':'之前有一些改变的代码: –