Ruby review for the final.


m = 0
# we are calling a method "times" on an object 5
# and are apssing the block in {} as an argument
5.times {|i| m = m + i * i}
puts m

# array methods:
# what will be printed?
[3, "hi", true,8.8].each {|x| puts x.is_a? String}


#Ruby hashes
# what will be printed by this fragment?
hash = {:a => 5, :b => 3, :c => 7, :d => 4}
k = nil
m = 0
hash.each do |key, value|
  if value > m
       k = key
       m = value
  end
end
puts k

# Ruby blocks and lambdas
def f pred, x,  y
  if pred.call(x) then x else y end
end

puts f lambda {|x| x < 5}, 7,  6

def g
  yield(1) + 2
end

puts g {|x| x * 2}

def h x
  yield(x * x)
end

puts h (2) {|y| y + 3}

# the same as the previous example
def h1 x, &b
  b.call(x * x)
end

puts h1 (2) {|y| y + 3}


CSci 4651 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.