有幾種方法在Ruby中清理它,我將在這裏展示:
puts 'Hello mate what is thy first name?'
name1 = gets.chomp
# Inline string interpolation using #{...} inside double quotes
puts "Your name is #{name1} eh? What is thy middle name?"
name2 = gets.chomp
# Interpolating a single string argument using the String#% method
puts 'What is your last name then %s?' % name1
name3 = gets.chomp
# Interpolating with an expression that includes code
puts "Oh! So your full name is #{ [ name1, name2, name3 ].join(' ') }?"
puts 'That is lovey!'
# Combining the strings and taking their aggregate length
puts 'Did you know there are %d letters in your full name?' % [
(name1 + name2 + name3).length
]
# Using collect and inject to convert to length, then sum.
puts 'Did you know there are %d letters in your full name?' % [
[ name1, name2, name3 ].collect(&:length).inject(:+)
]
的String#%
方法是sprintf
一個變種,是爲這種格式非常方便。它給你很多控制演示。
最後一個可能看起來有點彎曲,但Ruby的強大功能之一是能夠將一系列簡單的轉換串聯到一個有很多工作的東西中。
也就是說,如果你使用一個數組存儲的名稱,而不是三個獨立的變量部分看起來更加簡潔:
name = [ ]
name << gets.chomp
name << gets.chomp
name << gets.chomp
# Name components are name[0], name[1], and name[2]
# Using collect -> inject
name.collect(&:length).inject(:+)
# Using join -> length
name.join.length
它通常是安排在借給自己簡單的操作結構的東西是一個好主意,與其他方法交換,並且易於持久和恢復,例如從數據庫或文件中恢復。
是什麼問題?你在最後一行中引用了引號,順便說一句。 –
注意語法高亮,它會顯示你的語法錯誤。 – Aetherus
看起來你有一個額外的單引號後'你知道有'。另外,沒有像'Puts'這樣的方法,它應該是'puts'。 – BroiSatse