Tuesday, March 27, 2007

Loops @ Ruby

n.times {|i| puts i}

Well, the method Integer#times iterate self times (n in this) and for each iteration calls the block, gives it the current value।

something do |line|
#process something and line here
end

something' is a method and this method call the block with
some value.

For example if you want to read a file, you write

IO.foreach('file') do |line|
# do something with line
end

the method IO::foreach open the file given in argument, read each line and
call the block, given it the current line. At the end, IO::foreach close
the file



n.times {|i| puts i}

or

n.times do |i|
puts i
end


a=["hello","to","you"]
a.each {|i| puts i}

(1..10)each{|i| puts i}

or

for i in (1..10)
puts i
end



No comments: