سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

Underscore is simply a placeholder for the variable assignment you're doing there. In your case it basically means ignore the first value in the array. If we didn't have it, you'd do something like this:

ignored, foo, bar = ["", "foo", "bar"]
=> ["", "foo", "bar"]

then not use ignored for anything. It's nicer to use _

It's just a variable like any other. You could have used quux or whatever other name you like.

Except … you would get a warning about an unused local variable named quux, whereas variables whose names start with _ don't get a warning. This is an encoding of a convention to use _ as the name of a variable that you want to ignore.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top