Tags:
Forums: 

อยากรู้ว่า Loop แบบนี้ เขียนแบบไหนได้บ้าง

(1..10).each do |i|
  puts i
end

เปลี่ยนมาใช้ for

for i in (1..10)
  puts i
end

ใช้ปีกกาแทน do .. end

(1..10).each { |i| puts i }

อันนี้ไม่รู้จะเรียกว่าวน loop ได้หรือเปล่า แม่ว่าผลจะเหมือนเดิมแต่ action ไม่เหมือน

puts (1..10).to_a

ใช้ upto แทน for

1.upto(10) { |i| puts i }

ไม่ได้วน loop มั้ง

puts *(1..10)

...

Get latest news from Blognone
By: moniguna on 8 August 2008 - 13:07 #58393

10.times{ print it+1 }
1.upto(10){ print it }
(1..10).each{ print it }
print 1..10 //อันนี้ไม่ได้วนลูป แต่ผลลัพธ์หน้าตาคล้ายกัน

By: hereblur on 13 July 2008 - 16:15 #58426

10.times do |i| print i+1; end

By: DuRiAn on 7 August 2008 - 21:52 #60719

ruby นี่มันเยอะ(เกินไป?)จริงๆ

By: Sikachu
ContributoriPhoneIn Love
on 18 September 2008 - 03:00 #65140 Reply to:60719
Sikachu's picture

มันเยอะเกิน ก็จริงครับ
แต่ว่าส่วนใหญ่แล้ว มันจะมีแค่อย่างสองอย่างเท่านั้นแหละ ที่เข้ากับการใช้งาน

แล้วอีกอย่างนึง ถ้าเราเขียนอยู่เรื่อยๆ มันจะมีแค่อันเดียวแหละครับ ที่เราจะหยิบมาใช้บ่อยๆ ^^

บล็อกของผม: http://sikachu.com


บล็อกของผม: http://sikachu.com

By: lew
FounderJusci's WriterMEconomicsAndroid
on 8 August 2008 - 16:14 #60789
lew's picture


for i in xrange(10):
print i

อ่าว ผิดห้อง :P

LewCPE


lewcpe.com, @wasonliw

By: shelling
ContributoriPhoneAndroidUbuntu
on 18 September 2008 - 04:40 #65145
shelling's picture

ว่าจะเข้ามาตอบว่า ลังกาหลังสามรอบครึ่ง

แต่ลืมไป ไม่ใช่พันทิป ^ ^