Using underscores with characters in Ruby

I followed the Why (Poignant) Ruby Guide through a couple of other Ruby style guides to find out how rubists think. But this is the first time I see trailing underscores . What are these things? Are they useful, and if so, when do we use them and how to use them with splat operators?

(The link to the Ruby style guide is tied to the actual example)

+4
source share
2 answers

The name of the legal variable _. And something like *_like *x. The term "final underscore variable" actually refers to the last variable name in a comma-separated sequence of variables on the left side of the assignment operator, for example:

a, b, _ = [1, 2, 3, 4]

The splat operator has two uses:

  • Enter an array into individual elements.
  • Collect the elements into an array.

Which of these events depends on the context in which the splat operator is used.

Here are the examples that are said in the Ruby style guide:

a, b, _ = *foo

The final underscore variable is not needed in this example, because you can assign the first two elements footo variables aand bby writing:

a, b = *foo

, , , , , , a b.

, * (: Cary Swoveland):

a, b = [1, 2, 3]
p a, b

--output:--
1
2

* :

x, y, z = 10, [20, 30]
p x, y, z

--output:--
10
[20, 30]
nil

x, y, z = 10, *[20, 30]
p x, y, z

--output:--
10
20
30

, , * .

:

a, _, _ = *foo

:

a, _, _ = *[1, 2, 3, 4]
p a, _

puts "-" * 10

a, _ = *[1, 2, 3, 4]
p a, _

--output:--
1
3
----------
1
2

, :

 a, _, _
 ^  ^  ^
 |  |  |
[1, 2, 3, 4]

, , a . ?

a = *[1, 2, 3, 4]
p a

--output:--
[1, 2, 3, 4]

. . , , :

a, = *[1, 2, 3, 4]
p a

--output:--
1

:

a, *_ = *foo

:

a, = *foo 

.

, :

, , , .

, - :

*a = *[1, 2, 3, 4]
p a

--output:--
[1, 2, 3, 4]

, a , :

*a, _ = *[1, 2, 3, 4]
p a

--output:--
[1, 2, 3]

- :

*a, = *[1, 2, 3, 4]

--output:--
*a, = *[1, 2, 3, 4]
     ^
1.rb:6: syntax error, unexpected '\n', expecting :: or '[' or '.'

:

*a, b, _ = *foo

, foo b.

:

a, _b = *[1, 2, 3, 4]
a, _b, = *[1, 2, 3, 4]

:

a, _b = *[1, 2, 3, 4]
p a, _b

puts "-" * 10

a, _b, = *[1, 2, 3, 4]
p a, _b

--output:--
1
2
----------
1
2

, _b, _ b. , Erlang, _ _b b , Ruby.

, - .

+8

_ , (I.e., ).

Ruby, Ruby @ LaTeX. , "", "", "" "". "".

1. , :

items = [1, 2, 3]
items.each{|item| ...}

, , , :

is = [1, 2, 3]
is.each{|i| ...}

, , . :

item = [1, 2, 3]
item.each{|_item| ...}

x = [1, 2, 3]
x.each{|_x| ...}

2. , , , , . :

def foo a, b
  ... # Do something just a bit here
  _foo(a, b)
end
def _foo a, b
  ... # Do still a bit here
  __foo(a, b)
end
def __foo a, b
  ... # Most of the job is done here
end

3. , Ruby ( ) ( ). send, __send__. , send - , __send__ .

+1

Source: https://habr.com/ru/post/1610686/


All Articles