Recent Changes - Search:

edit SideBar


Firefox 2
Get Thunderbird!

CodeblocksIterations

Code Blocks and Iterations

#!/usr/bin/ruby
#
# code blocks and iterations
#

#array-each
[1,2,3,4].each do |x|
	puts "x: #{x}"
end

#upto
1.upto(5) do |x|
	puts x
end

#hash-each
{"a" => 1, "b" => 2}.each do |k,v|
	puts "k: #{k} v: #{v}"
end

#array-select
a = [1,2,49,100,111].select { |x| x < 50 } 
puts a

#blok olu&#351;turulmas&#305;
block = lambda { |x| puts x }
block.call "roger that!"

#parametre olarak block kabul eden fonksiyon yaz&#305;lmas&#305;(1)
#Ruby'de bir methodun blok kabul etmesi i�in ekstra bi&#351;ey
#yapmaya gerek yokmu&#351;. Sadece method'da yield'&#305;n olmas&#305; yeterli.
def call_twice
	puts "x"
	yield
	puts "y"
	yield
end
call_twice { puts "z" }

#parametre olarak block kabul eden fonksiyon yaz&#305;lmas&#305;(2)
#paramete olarak girilen blo&#287;u n'in de&#287;eri kadar yazar.
def repeat(n)
	if block_given?
		n.times { yield }
	else
		raise ArgumentError.new("Blok yoksa, tekrar da yok!")
	end
end
repeat(3) { puts "Repeat after me!" }

#Blo&#287;una arguman g�nderen method
def call_twice2
	puts "aa"
	r1 = yield("birinci")
	puts "r1: #{r1}"
	puts "bb"
	r2 = yield("ikinci")
	puts "r2: #{r2}"
end
call_twice2 do |y|
	puts "block: #{y}"
	y == "birinci" ? 1 : 2
end

#E&#287;er method'da yield varsa ve method'a blok g�nderilmiyorsa
#ruby istisna f&#305;rlat&#305;r.
#[1,2,3].each

#Bir kod blo&#287;unun bir de&#287;i&#351;kenle ba&#287;da&#351;t&#305;r&#305;l&#305;p(bind) 
#bir method'a parametre olarak g�ndermek.
#NOT: Kod blok arguman&#305; son arguman olmal&#305;!
def repeat2(n, &block)
	n.times { yield } if block
	#veya 
	#n.times { block.call } if block
end
repeat2(3) { puts "Copy that!" }

#Blok d&#305;&#351;&#305;nda tan&#305;mlanan de&#287;i&#351;kenlerin blok i�inde kullan&#305;lmas&#305;
var = 3
position = lambda do 
	puts "var: #{var}" 
end
position.call
var = 5
position.call

#Iterasyonun durdurulmas&#305;(break)
#NOT: Proc.new ile tan&#305;mlanan bir blokta "break" kullan&#305;lamaz,
#o y�zden blo&#287;u "lambda" ile olu&#351;turmak daha makul olurmu&#351;. 
3.upto(10) do |x|
	puts "x: #{x}"
	break if x == 5
end

#Kaynaklar:
#O'Reilly Ruby Cook Book

Edit - History - Print - Recent Changes - Search
Page last modified on December 01, 2006, at 01:43 AM