Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > iterating through a block; declaring an index/counter within that block

Reply
Thread Tools

iterating through a block; declaring an index/counter within that block

 
 
Thufir
Guest
Posts: n/a
 
      10-20-2007
Where does "food" come from in the example below? The declaration is
within the block? The varaible food exists only within the block?
What is (are) the value(s) for "food"?




Read the following aloud to yourself.

['toast', 'cheese', 'wine'].each { |food| print food.capitalize }

While this bit of code is less readable and sentence-like than the
previous examples, I'd still encourage you to read it aloud. While
Ruby may sometimes read like English, it sometimes reads as a shorter
English. Fully translated into English, you might read the above as:
With the words 'toast', 'cheese', and 'wine': take each food and print
it capitalized.

The computer then courteously responds: Toast, Cheese and Wine.

<http://poignantguide.net/ruby/chapter-3.html#section1>





thanks,

Thufir

 
Reply With Quote
 
 
 
 
7stud --
Guest
Posts: n/a
 
      10-20-2007
Thufir wrote:
> Where does "food" come from in the example below? The declaration is
> within the block? The varaible food exists only within the block?
> What is (are) the value(s) for "food"?
>
>
>
>
> Read the following aloud to yourself.
>
> ['toast', 'cheese', 'wine'].each { |food| print food.capitalize }
>


That thing on the right of each, between the braces, is a similar to a
method definition:


def func(food)
print food.capitalize
end

food is the parameter variable and you would call func like this:

func('toast')

'toast' then gets assigned to the parameter variable food.

each() is also method. each() is defined to pass each member of the
thing to its left to the block on its right. It is similar to doing
this:

def each(arr)
count = 0

while count < arr.length
curr_elmt = arr[count]
my_func(curr_elmt)
count += 1
end

end


def my_func(food)
print food.capitalize
end

arr = ['toast', 'cheese', 'wine']
each(arr)

--
Posted via http://www.ruby-forum.com/.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
problem in running a basic code in python 3.3.0 that includes HTML file Satabdi Mukherjee Python 1 04-04-2013 07:48 PM
Iterating a std::vector vs iterating a std::map? carl C++ 5 11-25-2009 09:55 AM
Iterating through class names using a block Ge Bro Ruby 16 11-26-2007 07:48 AM
Fo:Block can you check to see if a block contains any text by using the block id? morrell XML 1 10-10-2006 07:18 PM



Advertisments