Ruby /
CodeblocksIterationsCode 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şturulması block = lambda { |x| puts x } block.call "roger that!" #parametre olarak block kabul eden fonksiyon yazılması(1) #Ruby'de bir methodun blok kabul etmesi i�in ekstra bişey #yapmaya gerek yokmuş. Sadece method'da yield'ın olması yeterli. def call_twice puts "x" yield puts "y" yield end call_twice { puts "z" } #parametre olarak block kabul eden fonksiyon yazılması(2) #paramete olarak girilen bloğu n'in değ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ğ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ğer method'da yield varsa ve method'a blok g�nderilmiyorsa #ruby istisna fırlatır. #[1,2,3].each #Bir kod bloğunun bir değişkenle bağdaştırılıp(bind) #bir method'a parametre olarak g�ndermek. #NOT: Kod blok argumanı son arguman olmalı! def repeat2(n, &block) n.times { yield } if block #veya #n.times { block.call } if block end repeat2(3) { puts "Copy that!" } #Blok dışında tanımlanan değişkenlerin blok i�inde kullanılması var = 3 position = lambda do puts "var: #{var}" end position.call var = 5 position.call #Iterasyonun durdurulması(break) #NOT: Proc.new ile tanımlanan bir blokta "break" kullanılamaz, #o y�zden bloğu "lambda" ile oluşturmak daha makul olurmuş. 3.upto(10) do |x| puts "x: #{x}" break if x == 5 end #Kaynaklar: #O'Reilly Ruby Cook Book |