yield
kullanılır. Mevcut yönteminden
[1, 2, 3].each {|elem| puts elem}
return
çıkışlar ve dönüş değeri olarak "argüman" kullanır: Çok gibi, yöntem ve onun parametreleri sonra blok (küme parantezi temelde sadece kodu) yerleştirerek bunu gibi pek:
def hello
return :hello if some_test
puts "If it some_test returns false, then this message will be printed."
end
Ama sen herhangi yöntemlerde dönüş anahtar kelimeyi kullanmayı var unutmayın; Ruby, iade yapılmazsa değerlendirilen son ifadeyi döndürür. Böylece bu iki equivelent gibidir:
# A simple iterator that operates on an array
def each_in(ary)
i = 0
until i >= ary.size
# Calls the block associated with this method and sends the arguments as block parameters.
# Automatically raises LocalJumpError if there is no block, so to make it safe, you can use block_given?
yield(ary[i])
i += 1
end
end
# Reverses an array
result = [] # This block is "tied" to the method
# | | |
# v v v
each_in([:duck, :duck, :duck, :GOOSE]) {|elem| result.insert(0, elem)}
result # => [:GOOSE, :duck, :duck, :duck]
Ve bir sayı happy olup olmadığını görmek için bir yöntem uygulamak için kullanacaktır return
için bir örnek:
def explicit_return
# ...
return true
end
def implicit_return
# ...
true
end
İşte
bir yield
için örnek :
class Numeric
# Not the real meat of the program
def sum_of_squares
(to_s.split("").collect {|s| s.to_i ** 2}).inject(0) {|sum, i| sum + i}
end
def happy?(cache=[])
# If the number reaches 1, then it is happy.
return true if self == 1
# Can't be happy because we're starting to loop
return false if cache.include?(self)
# Ask the next number if it's happy, with self added to the list of seen numbers
# You don't actually need the return (it works without it); I just add it for symmetry
return sum_of_squares.happy?(cache << self)
end
end
24.happy? # => false
19.happy? # => true
2.happy? # => false
1.happy? # => true
# ... and so on ...
Bu yardımcı olur umarız!
Bloklara verilen link bozuk – adamscott
İşte iyi bir tane [link] (http://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes) – adamscott
teşekkürler @adamscott, linki seninkiyle değiştirdim. şerefe – Deleteman