-
Notifications
You must be signed in to change notification settings - Fork 1
04 iteration
View the source code.
File
ruby iteration.rb
Interpreter
irb(main):002:0> [2, 3, 5, 7, 11, 13].each {|p| puts p*p}
4
9
25
49
121
169
=> [2, 3, 5, 7, 11, 13]
Demonstrates iterator methods and loops.
In Ruby, we can associate a block of code with a method invocation.
The number 1 is object, an instance of the Fixnum class.
Fixnum inherits from the
Integer class.
And the Ingeger class defines an
upto method.
The upto method is an iterator. We associate an invocation of the
upto method with a block of code: {|j| print j}.
irb(main):033:0* 1.class
=> Fixnum
irb(main):034:0> Fixnum.superclass
=> Integer
irb(main):035:0> 1.upto(4) {|j| print j}
1234=> 1
The array [5, 2, 4] is an object, an instance of the Array class. And the Array class defines an each method. The each method is an iterator. We associate an invocation of the each method with a block of code.
irb(main):036:0> [5, 2, 4].class
=> Array
irb(main):038:0> [5, 2, 4].each {|j| print j}
524=> [5, 2, 4]
The Hash class also defines an each method.
irb(main):039:0> {:steve=>63, :nick=>23}.class
=> Hash
irb(main):040:0> {:steve=>63, :nick=>23}.each {|k,v| print "#{k} is #{v}. "}
steve is 63. nick is 23. => {:steve=>63, :nick=>23}
The Range class also defines an each method.
irb(main):041:0> (3..7).each {|j| print j}
34567=> 3..7
We can use arrays, hashes, and ranges in for loops.
irb(main):042:0> for j in [5, 4, 1] do
irb(main):043:1* print j
irb(main):044:1> end
541=> [5, 4, 1]
irb(main):045:0> for p in {:steve=>63, :nick=>23} do
irb(main):046:1* puts p
irb(main):047:1> end
steve
63
nick
23
=> {:steve=>63, :nick=>23}
irb(main):048:0> for j in (1...5) do
irb(main):049:1* print j
irb(main):050:1> end
1234=> 1...5
And we also have a while loop.
irb(main):060:0> b = 500
=> 500
irb(main):061:0> while b < 700
irb(main):062:1> b *= 1.09
irb(main):063:1> print b, " "
irb(main):064:1> end
545.0 594.0500000000001 647.5145000000001 705.7908050000002 => nil