user8773096
user8773096

Reputation:

What is this syntax called? { |n| "user#{n}" }

{ |n| "user#{n}" }

The curly braces with two pipes. This is a ridiculous question, I know, but trying to google what the name of this syntax is has proven to be impossible.

Upvotes: 2

Views: 101

Answers (2)

UsamaMan
UsamaMan

Reputation: 705

It’s called a block. There are two types of blocks in ruby. One is this syntax in curly braces and second is the do end. These both are interchangeable but the curly braces have higher precedence. Therefore these programs are interchangeable:

my_array.each do |element|
  puts element
end


my_array.each {|element|
  puts element
}

This post discusses in good detail the difference between the two and when they aren’t interchangeable.

Upvotes: 5

Carcigenicate
Carcigenicate

Reputation: 45750

This appears to be called a "code block".

It seems to essentially be an anonymous function. n is the parameter of the function in this case.

Upvotes: 1

Related Questions