How Add Elements an Array and Automatically Remove Duplicates in Ruby
- Categories:
- ruby
Operator |=
is bitwise OR assignment in Ruby. While working with Array, using |=
operator will automatically add elements and remove duplicates.
a = [1,2,2,3,3]
# => [1,2,2,3,3]
b = [3,4,5]
# => [3,4,5]
# a |= b is shorthand for a = a | b
a |= b
# => [1,2,3,4,5]
# Array with element of string can use |= operator too
x = ['aa', 'bb']
# => ['aa', 'bb']
y = ['b', 'cc']
# => ['b', 'cc']
x |= y
# => ['aa', 'bb', 'b', 'cc']
- Tags:
- #ruby