Use underscore as variable in Parallel Assignment
irb, ruby
Solution
In parallel assignment, we sometimes do two things :
- ignore one element ( taking care of `_`)
You can reuse an underscore to represent any element you don’t care about:
a, _, b, _, c = [1, 2, 3, 4, 5]
a # => 1
b # => 3
c # => 5
- ignore multiple elements ( taking care of `*` )
To ignore multiple elements, use a single asterisk — I’m going to call it a ‘naked splat’ for no better reason than that it sounds a bit amusing:
a, *, b = [1, 2, 3, 4, 5]
a # => 1
b # => 5
Read this blog post Destructuring assignment in Ruby to know more other related things.
Problem
In the following, variable `_` (underscore) is an `Array`, `foo == "foo"`, and `bar == "bar"`. ``` _, foo, bar = ["", "foo", "bar"] _ # => ["", "foo", "bar"] ``` Can someone explain what the underscore does and where it is useful to use?