ruby - Some code that I don't understand -
i don't understand while true
, name = gets(',').chomp(',')
, relationship. me, seems infinite loop. explain this?
print "enter more names separated commas: " while true name = gets(',').chomp(',') puts "hello #{name}" end
it is infinite loop. program never end (except crash on input). breaking down:
while true
this start while loop condition true loop forever on code end
.
name = gets(',')
see documentation gets. if run program directly, wait "line" of input on stdin
(the console/terminal). input read record separator, "," , result assigned variable name
.
.chomp(',')
chomp
method on string removes record separator end of string (again, ',' in case).
puts "hello #{name}"
this prints string "hello #{name}" value of name
variable interpolated #{} placeholder.
end
this ends while loop.
if run program , type "mary, angela, andy" , press enter will:
- read "mary," stdin,
chomp
"," off end, , assign "mary"name
variable. - print "hello mary" stdout.
- loop top, read "angela,", etc...
- loop top, , wait because there not record separator on stdin.
if type "foo," , press enter, will:
- read "andy\nfoo," stdin,
chomp
"," off end, etc... - print "hello andy\nfoo" stdout
so pretty lousy program given ostensibly trying do, there have it.
Comments
Post a Comment