40

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?

2
  • 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: stackoverflow.com/search?q=%5Bruby%5D+blocks
    – Phrogz
    Jan 29, 2011 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". It's a bit out of date, but those basics still apply. Jan 29, 2011 at 22:02

2 Answers 2

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

1
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:

3
  • 2
    1. No one calls them 'goal posts'. 2. They are not named arguments 3. You are not 'iterating over them'
    – horseyguy
    Jan 30, 2011 at 4: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, 2011 at 19:01
  • 1. blog.teamtreehouse.com/ruby-arrays "goalposts" (c.2006). Mar 16 at 1:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.