[英]Formatting issue with Ruby and puts
When we were younger, my friend and I had our own secret language. 小时候,我和我的朋友有我们自己的秘密语言。 Recently he challenged me to make a translator so that I could input a word and it would convert it to the right word.
最近,他向我提出挑战,要求我翻译,以便我可以输入一个单词并将其转换为正确的单词。 It's silly, but it was just for fun.
这很愚蠢,但这只是为了好玩。
The problem I have is that the converted word output is on separate lines. 我的问题是转换后的单词输出在单独的行上。
What it should do: 它应该做什么:
Word to translate: Banana 翻译的词:香蕉
Translated word: ananabang 翻译的词:ananabang
What it does: 它能做什么:
Word to translate: Banana 翻译的词:香蕉
Translated word: 翻译词:
anana 安娜娜
bang 砰
This is the code I've written. 这是我编写的代码。
puts "Enter word to translate \n \n"
input = gets
firstCharacter = input[0].chr
ang = "ang"
if firstCharacter =~ /\A(a|b|c|d|A|B|C|D)\Z/
input.slice!(0)
puts firstCharacter + input + "ang"
end
I wonder if anyone can help me with the outputting issue..? 我想知道是否有人可以帮助我解决输出问题。
Thanks 谢谢
EDIT: Fixed it with gets.chomp. 编辑:用gets.chomp修复了它。
gets
returns the entered string with a newline at the end. gets
返回输入的字符串,末尾有换行符。 If you change your second line to input = gets.chomp
, it will work as expected because chomp
removes the trailing newline. 如果将第二行更改为
input = gets.chomp
,则它将按预期工作,因为chomp
会删除结尾的换行符。
You can also refactor your code into something more concise and clear: 您还可以将代码重构为更简洁明了的内容:
print "Enter word to translate: "
word = gets.chomp.downcase
puts word.sub(/^(.)/, '') << "#{$1}ang"
Or slightly more verbosely: 或更详细些:
print "Enter word to translate: "
word = gets.chomp.downcase
translation = word[1,1000] << word[0,1]
translation << 'ang'
puts translation
There are a lot of ways to do anything in Ruby, and it often pays to step back and consider whether you're overengineering when you could be creating something simpler and more maintainable. 在Ruby中,有许多方法可以执行任何操作,而退一步通常会值得考虑,当您可以创建更简单,更可维护的内容时,考虑您是否过度设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.