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


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...