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

User Input (gets)

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

Terminal app တွေမှာ user ဆီက data ယူချင်ရင် gets ကိုသုံးပါတယ်။ gets က user ရိုက်ထည့်ပြီး Enter နှိပ်တဲ့စာကိုယူပေးပါတယ်။ အဆုံးမှာ newline ပါလာတာကြောင့် .chomp နဲ့ဖယ်လေ့ရှိပါတယ်။

ruby
print "What's your name? "
name = gets.chomp

print "How old are you? "
age = gets.chomp.to_i

puts "Hello, #{name}. Next year you will be #{age + 1}."

print က line မဆင်းဘဲ prompt ပြပါတယ်။ gets.chomp က input စာကိုယူပြီး Enter newline ကိုဖယ်ပါတယ်။ to_i က string ကို integer ပြောင်းပါတယ်။

You should see
What's your name? Aung How old are you? 20 Hello, Aung. Next year you will be 21.

Info

User input က default အနေနဲ့ String ဖြစ်ပါတယ်။ Number အနေနဲ့တွက်ချင်ရင် to_i သို့မဟုတ် to_f ပြောင်းရပါမယ်။

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

  • age = gets.chomp လို့ပဲထားပြီး age + 1 တွက်ရင် String နဲ့ Integer ပေါင်းလို့ TypeError ဖြစ်နိုင်ပါတယ်။
User Input (gets) | Thuta Learning