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:

  1. read "mary," stdin, chomp "," off end, , assign "mary" name variable.
  2. print "hello mary" stdout.
  3. loop top, read "angela,", etc...
  4. loop top, , wait because there not record separator on stdin.

if type "foo," , press enter, will:

  1. read "andy\nfoo," stdin, chomp "," off end, etc...
  2. print "hello andy\nfoo" stdout

so pretty lousy program given ostensibly trying do, there have it.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -