如果我開始與兩個數組如:如何在ruby中合併兩個數組對象?
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
如何數組合併成一個數組這樣嗎?
arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
如果我開始與兩個數組如:如何在ruby中合併兩個數組對象?
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
如何數組合併成一個數組這樣嗎?
arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
p array1 + array2
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
或者,也許這是多餘的:
array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
array3 = [{ID:"3",name:"Duck"}]
p [array1, array2, array3].map(&:first)
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}, {:ID=>"3", :name=>"Duck"}]
我們可以刪除「:」嗎? –
否@TijeKusnadi,這是行不通的,那就是他們調用對象上的'to_proc'的方式,就等於寫下'.map {| e | e.first}',你可以選擇使用什麼。 –
只需加在一起:
irb(main):005:0> puts array1+array2
{:ID=>"1", :name=>"Dog"}
{:ID=>"2", :name=>"Cat"}
或者:
irb(main):006:0> p array1+array2
[{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
arraymerge = [{「ID」:「1」,「name」:「Dog」},{「ID」:「2」,「name」貓「}] –
我想數組符號仍然存在,我該怎麼做? –
它仍然是一個數組。 'puts'的打印方式與「p」的打印方式稍有不同。 – Kathryn
你的問題的完美答案是:
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
arraymerge = array1.concat(array2)
# Output: [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
請投票+1如果u喜歡我的答案!
你可以使用+
運營商做
array1 = [{"ID":"1","name":"Dog"}]
array2 = [{"ID":"2","name":"Cat"}]
arraymerge = array1 + array2
#=> [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
'數組1 +數組2#=> [{:ID => 「1」,:名稱=> 「狗」},{:ID => 「2」,:name =>「Cat」}]' –