Skip to content

Instantly share code, notes, and snippets.

@pinzolo
Last active August 29, 2015 13:55
Show Gist options
  • Save pinzolo/8701628 to your computer and use it in GitHub Desktop.
Save pinzolo/8701628 to your computer and use it in GitHub Desktop.
Array の加算メソッド比較

Array#push

  • 破壊的
base = [1,2,3]
added = base.push(4)
p added
  # => [1, 2, 3, 4]
p base
  # => [1, 2, 3, 4]
  • 複数引数可能
base = [1,2,3]
base.push(4,5)
  # => [1, 2, 3, 4, 5]
other = [6,7]
base.push(other)
  # => [1, 2, 3, 4, 5, [6, 7]]
base.push(*other)
  # => [1, 2, 3, 4, 5, [6, 7], 6, 7]

Array#<<

  • 破壊的
base = [1,2,3]
added = base << 4
p added
  # => [1, 2, 3, 4]
p base
  # => [1, 2, 3, 4]
  • 複数引数不可
base = [1,2,3]
base << 4, 5
  # => syntax error
other = [4,5]
base << other
  # => [1, 2, 3, [4, 5]]
base << *other
  # => syntax error
base.<<(*other)
  # => ArgumentError: wrong number of arguments (2 for 1)

Array#+

  • 非破壊的
base = [1,2,3]
added = base + [4]
p added
  # => [1, 2, 3, 4]
p base
  # => [1, 2, 3]
  • 引数は配列のみ
base = [1,2,3]
base + 4
  # => TypeError: no implicit conversion of Fixnum into Array
base + [4]
  # => [1, 2, 3, 4]
base + [5, 6]
  # => [1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment