程式扎記: [ 常見問題 ] How do you add an array to another array in Ruby

標籤

2014年10月30日 星期四

[ 常見問題 ] How do you add an array to another array in Ruby

Source From Here
Question
Consider we have two array:
>> somearray = ["some", "thing"]
>> anotherarray = ["another", "thing"]

How do we append all elements in anotherarray into somearray without ugly for-loop and get:
>> somearray
["some","thing","another","thing"]

How-To
I'm doubtless forgetting some approaches, but you can concatenate:
Way1
>> a1 = ["some", "thing"]
=> ["some", "thing"]
>> a2 = ["another", "thing"]
=> ["another", "thing"]
>> a1.concat a2
=> ["some", "thing", "another", "thing"]
>> a1
=> ["some", "thing", "another", "thing"]
>> a2
=> ["another", "thing"]

Way2
>> a3 = a1+a2
=> ["some", "thing", "another", "thing"]
>> a1
=> ["some", "thing"]
>> a2
=> ["another", "thing"]

or push/unshift:
Way3:
>> a1.push(*a2)
=> ["some", "thing", "another", "thing"]
>> a1
=> ["some", "thing", "another", "thing"]
>> a2
=> ["another", "thing"]

Way4:
>> a2.unshift(*a1)
=> ["some", "thing", "another", "thing"]
>> a1
=> ["some", "thing"]
>> a2
=> ["some", "thing", "another", "thing"]

or slice:
Way5:
>> a1[a1.size,0]=a2
=> ["another", "thing"]
>> a1
=> ["some", "thing", "another", "thing"]
>> a2
=> ["another", "thing"]

Way6:
>> a1[a1.size..0]=a2
=> ["another", "thing"]
>> a1
=> ["some", "thing", "another", "thing"]
>> a2
=> ["another", "thing"]

Way7:
>> a1.insert(a1.length, *a2)
=> ["some", "thing", "another", "thing"]
>> a1
=> ["some", "thing", "another", "thing"]
>> a2
=> ["another", "thing"]

or append and flatten - Way8:
>> (a1 << a2).flatten! # a call to #flatten instead would return a new array


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!