Ruby 茴香豆有幾種寫法之 Array 的合併

jprovim · February 13, 2015 · Last by pynix replied at February 14, 2015 · 2070 hits

Array

已知

a = [1,2,3]
b = [4,5,6] # or b = [4,5,6, [7,8,9]]
  1. a + b
  2. a.concat(b)
  3. push

    a.push(*b)
    a.unshift(*b)
    
  4. insert

    a[a.length, 0] = b
    a[a.length..0] = b
    a.insert(a.length, *b)
    
  5. flatten, (a1 << a2).flatten!

  6. a | b, 好吧,這個也算,這個是求 Unique 的。

  7. 6的變形

    a = [1,2,3]
    c = [4,5,6]
    a.each{|n| c = [n] | c }
    # => [3, 2, 1, 4, 5, 6]
    
  8. 再來一個用 << 來寫

    c= []
    a.each {|n| c<<n}
    

牛人 現身,繼續增加方法!

  1. @luikore

    [*a, *b]
    

Reference

1. 2.

1 Floor has deleted

Yukihiro Matsumoto: Ruby inherited the Perl philosophy of having more than one way to do the same thing. I inherited that philosophy from Larry Wall, who is my hero actually. I want to make Ruby users free. I want to give them the freedom to choose. People are different. People choose different criteria. But if there is a better way among many alternatives, I want to encourage that way by making it comfortable. So that's what I've tried to do. Maybe Python code is a bit more readable. Everyone can write the same style of Python code, so it can be easier to read, maybe. But the difference from one person to the next is so big, providing only one way is little help even if you're using Python, I think. I'd rather provide many ways if it's possible, but encourage or guide users to choose a better way if it's possible.

a+b 简单粗暴

You need to Sign in before reply, if you don't have an account, please Sign up first.