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


沒有留言:

張貼留言

[JS 文章收集] 用 Node.js 學 JavaScript 語言(1)簡介與安裝

Source From  Here   簡介   Node.js  是 Ryan Dahl 基於 Google 的 V8 引擎於 2009 年釋出的一個 JavaScript 開發平台,主要聚焦於 Web 程式的開發,通常用被來寫網站。但是,要開發網站就勢必要把「 HTML,...