What does the |variable| syntax mean? [duplicate]

痞子三分冷 提交于 2020-07-16 07:59:28

问题


What is the | | around profile below called, what does it mean, and why it is after do? I thought do is followed by a loop block or so.

ticks = get_all[0...MAX].map do |profile|
  # ...
end

回答1:


it's like a foreach, so profile will be a different value in each of the functions calls, one function call per element in get_all.

see this:

my_array = [:uno, :dos, :tres]
my_array.each do |item| 
    puts item
end



回答2:


They are part of the syntax for defining a block. The way I like to explain it is that the pipes look like a slide and those variables inside the pipes "slide" down into the block of code below them.

Essentially the variables in the pipes are available to the block. In the case of iteration the variable would represent an element in whatever you are iterating over.




回答3:


I'll use this example to try to explain the concept to you.

friends = ["James", "Bob", "Frank"]
friends.each { |friend| puts friend }

James
Bob
Frank

So here, we have an array of our friends: James, Bob, and Frank.

In order to iterate over them, we call the #each method on the array. The method will start with the first item in my array and call the block on it.

Essentially, the item that I'm currently iterating over is passed to the variable inside of the two pipe characters. You can call it |buddy| and change the block to { |buddy| puts buddy } and it would still do the same thing.




回答4:


The pipe characters delimit the parameter list of a block definition just like parentheses delimit the parameter list of a method definition. So, in this code snippet:

def foo(bar, baz) end

some_method_that_takes_a_block do |bar, baz| end

The parentheses and the pipes have the exact same purpose.



来源:https://stackoverflow.com/questions/19530077/what-does-the-variable-syntax-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!