Ruby 'gets' that works over multiple lines

試著忘記壹切 提交于 2019-12-01 15:25:06

You can do this in following way,

$/ = "END"  
user_input = STDIN.gets
puts user_input

make sure to type END keyword when you think the input is finished,

As well this will only work with actual interpreter not irb.

You can use this method, it accepts text until the first empty line

def multi_gets all_text=""
  while (text = gets) != "\n"
    all_text << text
  end
  all_text
end

or this one, you can replace the \n\n with any end character you define

def multi_gets all_text=""
  while all_text << STDIN.gets
    return all_text if all_text["\n\n"]
  end
end

You could use readlines() on $stdin like so

> $stdin.readlines
Mit Wohnungen, mit Bergen, Hügeln, Flüssen,
Solang ichs deutlich sah, ein Schatz der Freuden;
Zuletzt im Blauen blieb ein Augenweiden
An fernentwichnen lichten Finsternissen.

# ^D
 => ["Mit Wohnungen, mit Bergen, Hügeln, Flüssen,\n",
 "Solang ichs deutlich sah, ein Schatz der Freuden;\n",
 "Zuletzt im Blauen blieb ein Augenweiden\n",
 "An fernentwichnen lichten Finsternissen.\n"]
str = <<-EOF
Your multi line
text goes here
.....
EOF

But the catch is you'll have to end with EOF

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!