Ruby 转换和添加变量

Ruby 转换和添加变量,ruby,Ruby,我在获取由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.cho

我在获取由
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

有什么想法吗?

在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(:+)
]
该方法是的一个变体,对于这种格式非常方便。它让你对演讲有很大的控制权

最后一个可能看起来有点令人费解,但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
name=[]

出什么问题了?顺便说一句,你在最后一行中弄错了引号。请注意突出显示的语法,它显示了你的语法错误。在
“你知道有引号吗”
之后,你似乎多了一个引号。另外,没有像
put
这样的方法,它应该是
put
,并且不要使用字符串连接。用字符串插值代替。太棒了,谢谢!
#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?"