Ruby 列出项目直到empty gets返回填充的数组-不';连续填充阵列
我正在尝试制作一些东西,允许我运行列出大量单词,然后在我按下Enter键时返回一个排序数组,而不列出字符串。现在,提示符允许我键入两行,然后返回仅添加最后一个单词的数组,然后循环返回并再次开始,而不是连续向数组添加单词Ruby 列出项目直到empty gets返回填充的数组-不';连续填充阵列,ruby,arrays,Ruby,Arrays,我正在尝试制作一些东西,允许我运行列出大量单词,然后在我按下Enter键时返回一个排序数组,而不列出字符串。现在,提示符允许我键入两行,然后返回仅添加最后一个单词的数组,然后循环返回并再次开始,而不是连续向数组添加单词 def stuffsky other_one=[] puts "What would you like to add to the message? type a word please, then press Enter" while true if ge
def stuffsky
other_one=[]
puts "What would you like to add to the message? type a word please, then press Enter"
while true
if gets.chomp != "\n"
other_one.push(gets)
else
break
end
puts other_one
end
end
stuffsky
也许你想做这样的事
def stuffsky
other_one = []
puts "What would you like to add to the message? type a word please, then press Enter"
while true
word = gets.chomp
break if word == ""
other_one.push(word)
puts "other_one: #{ other_one.join(' ') }"
end
other_one
end
puts "stuffsky: #{ stuffsky }"
运行时,输出:
foo
other_one: foo
bar
other_one: foo bar
baz
other_one: foo bar baz
stuffsky: ["foo", "bar", "baz"]
加上你的逻辑是痛苦的。反转逻辑,以便在单词为空时中断,否则继续。每次引用
获取
时,实际上是在调用一个方法,该方法读取用户的一行输入并返回它。所以当你第一次说get.chomp!=“\n”
Ruby读入一行输入以检查您的情况,然后第二次当您说other\u one时。按下(获取)
Ruby读入第二行输入以添加到other\u one
。因此,您可以通过每个循环只调用一次get
来解决这个问题
您的代码还存在一些次要的代码质量/可读性问题。我可能会这样做:
# Extract line getter to seperate method
def gets_lines
result = []
loop do # Use loop instead of while true
line = gets.chomp # Note: chomp gets rid of the newline at the end of the string
break if line.empty? # A bit more readable than your other condition
result << line
end
return result
end
def stuffsky
puts "What would you like to add to the message? type a word please, then press Enter"
puts gets_lines.sort # You forgot to sort the array in your code
end
stuffsky
#提取行getter以分离方法
def获取_行
结果=[]
loop do#使用loop而不是while true
line=gets.chomp#注意:chomp去掉字符串末尾的换行符
如果行为空,则中断?#比你的其他条件更具可读性
结果你到底在问什么?你能澄清你在问什么吗?我在问为什么只要你继续在每一行上添加单词,运行这段代码就不会让数组充满单词。另外,询问如何修复。顺便说一句,非常感谢!我想我明白你所说的有缺陷的逻辑的意思了——如果GET真的这么做了,那么在GET之后立即中断就容易多了,而不是在GET没有接收到作为while循环逻辑一部分的输入时中断。这不仅仅是因为中断在它之后,还因为使用了!=“”
。我们倾向于使用否定的术语,但用肯定的方式陈述逻辑通常会使它更清晰、更简洁;换句话说,if word==”
比if word!="" ... 打断
,并允许我简化表达式的其余部分。谢谢!你知道有什么好书可以帮助程序员改进逻辑吗?我认为通读“Perl最佳实践”这本书是一个很好的开始,或者通读关于Perl的PBP模块的文档。实践背后的思想很好理解。然后,您可以为自己的编码实践做出决策,并注意权衡。我理解!谢谢:)
# Extract line getter to seperate method
def gets_lines
result = []
loop do # Use loop instead of while true
line = gets.chomp # Note: chomp gets rid of the newline at the end of the string
break if line.empty? # A bit more readable than your other condition
result << line
end
return result
end
def stuffsky
puts "What would you like to add to the message? type a word please, then press Enter"
puts gets_lines.sort # You forgot to sort the array in your code
end
stuffsky
What would you like to add to the message? type a word please, then press Enter
Apple
Orange
Aardvark
Lion
Tiger
Aardvark
Apple
Lion
Orange
Tiger