Pages

Wednesday 9 April 2014

Iterators in Ruby

1. It executes a block again and again.
2. In ruby array and hashes can be termed as collection.
3. Collection is basically a object that stores a group of data members.
4. Iterator return all the elements of collection.
5. Loops in ruby are used to execute the same block of code a specified number of times.

Ruby iterators.

1. Time : Will allow you to execute a loop
I = nil 3.times do |num|  i = num+1  puts i end

2. Each: returns the collection not the value
   Executes code for each element.
[1, 2, 3].each do |alpha|  puts “#{alpha}*2”end
result: 2,4.6
o. Each_Index:
[“a”, “b”, “c”].each do |alpha|  puts “#{alpha}” end
result: 0,1,2
o. Range
(0..5).each do |i|  # code end

3. Collect, Map:
  Collect returns all the elements of the collection.

   Collects what ever values are returned from each iteration of the block
a = [1,2,3] c = a.collect b= {“a” => 1, “b” => 2} d = b.collect
puts c.inspect puts d.inspect
results
[1,2,3] [["a",1],["b", 2]]

o Use Collect: to do something with Each of the value to get the new array
a = [1,2,3] b = a.collect{|x| 10*x} puts b.inspect
results [10, 20, 30]

4. loop iterators: for infinite loop
loop {puts "Hello"}
result
Hello, Hello, Hello etc
    so it needs control keywords and terminators like
i = 0
loop do  i += 1  print i  break if i==10 end
results: 1 2 3 4 5 6 7 8 9 10

5. Upto: We execute from number x to number y
1.upto(10) {|i| puts I}
similarly downto:
10.downto(1) {|i| puts I}
Results: 1 2 3 4 5 6 7 8 9 10
6. Step:
      Step to iterate While skipping over the range of number
1.step(10, 2){|i| puts i} results: 1 3 5 7 9

7. while
while condition do  code end
8. While modifier
begin    code end while condition
9. Until
until condition do    code end
10. for loop:
for i in 0..5    puts i end



No comments:

Post a Comment