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

jprovim · 2015年02月13日 · 最后由 pynix 回复于 2015年02月14日 · 2075 次阅读

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 楼 已删除

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 简单粗暴

需要 登录 后方可回复, 如果你还没有账号请 注册新账号