转换和添加变量

时间:2016-02-22 15:41:19

标签: 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.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

任何想法?

2 个答案:

答案 0 :(得分: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

通常一个好主意是在结构中组织事物,使其易于操作,与其他方法交换,并且易于持久化和恢复,例如从数据库或文件中恢复。

答案 1 :(得分: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?"