Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Blocks & Yield

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Block သည် method call နောက်မှာလိုက်လာတဲ့ code chunk ဖြစ်ပါတယ်။ Ruby iterator တွေ၊ file handling, callbacks တွေမှာ block ကို မကြာခဏတွေ့ရပါတယ်။ Method ထဲကနေ block ကို run ချင်ရင် yield သုံးနိုင်ပါတယ်။

ruby
def with_loading
  puts "Loading..."
  yield
  puts "Done!"
end

with_loading do
  puts "Fetching user data"
end

with_loading method ကိုခေါ်တဲ့အခါ block ကိုပါပေးလိုက်ပါတယ်။ Method ထဲက yield ရောက်တဲ့နေရာမှာ block ထဲက code run ပါတယ်။

You should see
Loading... Fetching user data Done!

Info

Block မပေးဘဲ yield ခေါ်ရင် error ဖြစ်နိုင်ပါတယ်။ လိုအပ်ရင် block_given? နဲ့စစ်နိုင်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Block parameter တွေရှိလာတဲ့အခါ |value| syntax ကိုမမေ့ပါနဲ့။ ဥပမာ items.each { |item| puts item } ။
Blocks & Yield | Thuta Learning