Sonntag, 11. Oktober 2009

RUBY codes: code blocks and iterations

from "Ruby Cookbook" O'Reilly
for detailed information, look this book


[1,2,3].each { |i| puts i }

[1,2,3].each do |i|
if i%2 == 0
puts "="
else
puts "!"
end
end

1.upto 3 do |x| # same 1.upto(3)

1.upto(3) { |x| ... } # ok
1.upto 3 { |x| ... } # error


log = lambda { |str| puts "[LOG] #{str}" }
log.call("A test log message.")


{1=>2, 2=>4}.each { |k,v| puts "Key #{k}, value #{v}" }


def times_n(n)
lambda { |x| x * n }
end

times_ten = times_n(10)
times_ten.call(5) # => 50

circumference = times_n(2*Math::PI)
[1, 2, 3].collect(&circumference)
# => [6.28318530717959, 12.5663706143592, 18.8495559215388]


Clousure:
Every Ruby block is also a closure.

ceiling = 50
[1, 10, 49, 50.1, 200].select { |x| x < ceiling }
# => [1, 10, 49]

the var celing is context depended.

Lambda and Proc


block = { |x| puts x } # error
block = lambda { |x| puts x } # ok
block.call "bla bla!"


def my_lambda(&aBlock) # a block in function parameters
aBlock
end

b = my_lambda { puts "Hello World My Way!" }
b.call
b.class # => Proc

aBlock = Proc.new { |x| puts x }
aBlock = proc { |x| puts x }
aBlock = lambda { |x| puts x }


add_lambda = lambda { |x,y| x + y }
add_lambda.call(4,5,6) # ArgumentError: wrong number of arguments (3 for 2)

add_procnew = Proc.new { |x,y| x + y }
add_procnew.call(4,5,6) # => 9



Yielding


def myfunc
puts "1"
yield
puts "2"
yield
end

myfunc("3")
# 1
# 3
# 2
# 3


def repeat(n)
if block_given?
n.times { yield }
else
raise ArgumentError.new("I can't repeat a block you don't give me!")
end
end

repeat(4) { puts "Hello." }
# Hello.
# Hello.
# Hello.
# Hello.

repeat(4)
# ArgumentError: I can't repeat a block you don't give me!

Keine Kommentare:

Kommentar veröffentlichen