41

While reading some Ruby code I saw this:

create_table :talks do |t|

What is this notation |variable|? What does that do?

And also, where do I find help for these specific subjects like | |, #{}, and so on?

nbro
  • 15,395
  • 32
  • 113
  • 196
pedrozath
  • 2,353
  • 4
  • 20
  • 23
  • It's so hard to figure out which of the many questions about Ruby block syntax might best be considered a duplicate, I'll just suggest this search term instead: http://stackoverflow.com/search?q=%5Bruby%5D+blocks – Phrogz Jan 29 '11 at 17:28
  • "where do i find help for these specific subjects...". Those are very basic, core-to-Ruby things so, at a minimum, read through the online version of ["Programming Ruby"](http://www.ruby-doc.org/docs/ProgrammingRuby/). It's a bit out of date, but those basics still apply. – the Tin Man Jan 29 '11 at 22:02

2 Answers2

26

It's a way of defining arguments for a block, in a similar way to def methodname(arg1, arg2)

A nice explanation of blocks is available from Robert Sosinski

Gareth
  • 133,157
  • 36
  • 148
  • 157
  • 1
    https://www.rubyguides.com/2016/02/ruby-procs-and-lambdas/ This article has a better explanation. – Jin Lim Dec 12 '19 at 23:23
22

You may also hear them referred to as goal posts. They are essentially named arguments that one can use to iterate over the data within a collection. For example, with an array:

# Print 1 2 3 4
[1,2,3,4].each do |e|
    print "#{e} "
end

Or with a key, value map, you would have multiple arguments between the goal posts

m = {"ruby" => "rails", "groovy" => "grails", "scala" => "lift", "java" => "spring"}
m.each do |lang, framework|
    # print the keys first - "ruby groovy scala java"
    print "#{lang} "
    # print the values second - "rails grails lift spring" 
    print "#{framework} "
end

Your question sounds more specific to the Ruby language than Ruby on Rails. I would check out some of these links:

Warren Dew
  • 8,790
  • 3
  • 30
  • 44
rynmrtn
  • 3,371
  • 5
  • 28
  • 44
  • 2
    1. No one calls them 'goal posts'. 2. They are not named arguments 3. You are not 'iterating over them' – horseyguy Jan 30 '11 at 04:26
  • 2
    1. debatable; 2. Splitting hairs on words; the Ruby documentation refers to them as parameters, not named arguments; 3. Perhaps 'iterating' is not 100% correct, but the premise remains the same - the code block is called for each element in the collection. – rynmrtn Jan 30 '11 at 19:01
  • 1. https://blog.teamtreehouse.com/ruby-arrays "goalposts" (c.2006). – Todd Sprang Mar 16 '23 at 01:59