tags:

views:

317

answers:

3
temp = 98.3
begin
print "Your temperature is " + temp.to_s + " Fahrenheit. "
puts "I think you're okay."
temp += 0.1
end while temp < 98.6

In the above example, is everything between begin and end a block?

I'm still confused what a block is.

If you can't call it a block, what would you call that chunk of code between begin and end? Is it ok to call it a chunk?

+4  A: 

From Agile Web Development with Rails (The introduction to Ruby section)

Code blocks are just chunks of code between braces or between do...end. A common convention is that people use braces for single-line blocks and do/end for multiline blocks.

{ puts "Hello" }    # this is a block 
do                  ### 
club.enroll(person) # and so is this 
person.socialize    # 
end                 ###
Jason Punyon
+9  A: 

Block has a special meaning in Ruby. According to Matz, Ruby's creator, you can look at a block as a nameless function - typically something that can be yielded into, and which may also take parameters.

You may see the following kind of disamiguation when describing Ruby syntax:

  • begin...end (what is called block in other languages) may sometimes be referred to simply as what it is, i.e. an expression (which may in turn contain other expressions - an expression is simply something that has a return value) in Ruby. Some references will still call it a begin/end block, or a code block, adding somewhat to the confusion
  • do...end or {...} will always be referred to as a block in Ruby

For examples, peruse the the Ruby syntax man page, e.g.

begin expression end
expression while expression
loop block

For further reading, see:

Cheers, V.

vladr
+1  A: 

begin/end are strictly control flow, not blocks.

begin
  puts "hi"
end
# => "hi"

The code runs immediately. If it was a block, it would have to been called somehow in order for the code in it to run, as in this example:

def a_method; end
a_method { puts "hi" }
# nothing..

def a_method
  yield
end

a_method { puts "Hi!" }
# => "Hi!"
August Lilleaas