2016-02-22 32 views
-3

我無法接受由gets.chomp給出的變量,並將其添加到另一個變量或整數。轉換和添加變量

puts 'Hello mate what is thy first name?' 
name1 = gets.chomp 
puts 'Your name is ' + name1 + ' eh? What is thy middle name?' 
name2 = gets.chomp 
puts 'What is your last name then ' + name1 + '?' 
name3 = gets.chomp 
Puts 'Oh! So your full name is ' + name1 + ' ' + name2 + ' ' + name3 + ' ?' 
puts 'That is lovey!' 
puts 'did you know there are ' ' + name1.length.to_i + '+' + 'name2.length.to_i + '+' + name3.length.to_i + '' in your full name 

任何想法?

+1

是什麼問題?你在最後一行中引用了引號,順便說一句。 –

+2

注意語法高亮,它會顯示你的語法錯誤。 – Aetherus

+2

看起來你有一個額外的單引號後'你知道有'。另外,沒有像'Puts'這樣的方法,它應該是'puts'。 – BroiSatse

回答

1

有幾種方法在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 

它通常是安排在借給自己簡單的操作結構的東西是一個好主意,與其他方法交換,並且易於持久和恢復,例如從數據庫或文件中恢復。

+0

輝煌,謝謝! –

0
#I think using "#{variable_name}" would be easier to achieve your goal, just 
#stay away from the single quotes when using this form of string   
#interpolation. 
puts "Hello mate what is thy first name?" 
name1 = gets.chomp 
puts "Your name is #{name1} eh? What is thy middle name?" 
name2 = gets.chomp 
puts "What is your last name then #{name1}?" 
name3 = gets.chomp 
puts "Oh! So your full name is #{name1} #{name2} #{name3}?" 
puts "That is lovey!" 
puts "Did you know there are '#{name1.length + name2.length + name3.length}' letters in your full name?"