Source From HereQuestionConsider 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-ToI'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
沒有留言:
張貼留言