Ruby 2.3。如何将用户输入字符串转换为数组,然后将其拆分为单个元素?

时间:2016-11-03 05:39:15

标签: arrays ruby

Ruby noob在这里。我已经在这几个小时了,但我无法弄清楚如何存储用户输入,将其转换为数组,然后将数组拆分为单独的元素。

puts "Hey! What's up?"

response = Array.new
response << gets.chomp

crypt = response.each_slice(3).to_a
print crypt

这是输出的内容:

Hey! What's up?
Nothin
[["Nothin"]]

这就是我想要的,但无法弄清楚:

[["N", "o", "t", "h", "i", "n"]]

我看过Ruby文档却感到困惑,所以经过几个小时的试验和错误,我就在这里。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

使用:

puts "Hey! What's up?"

crypt = gets.chomp

p [crypt.split("")]

答案 1 :(得分:0)

这就是我如何做到你需要的:

puts "Hey! What's up?"

response = Array.new
input = gets.chomp

response << input.split("")

puts response.to_s

运行此代码即可

Hey! What's up?
Nothin
[["N", "o", "t", "h", "i", "n"]]