为什么我不能打印常量字符串的长度? 这是我的代码:
#!/usr/bin/ruby
Name = "Edgar Wallace"
name = "123456"
puts "Hello, my name is " + Name
puts "My name has " + Name.to_s.length + " characters."
我已经读过“How do I determine the length of a Fixnum in Ruby?”,但不幸的是它对我没有帮助。
尝试后,报错:
./hello.rb:7:in `+': can't convert Fixnum into String (TypeError)
from ./hello.rb:7:in `<main>'
最佳答案
您不能连接到带有 Fixnum 的字符串:
>> "A" + 1
TypeError: can't convert Fixnum into String
from (irb):1:in `+'
from (irb):1
from /usr/bin/irb:12:in `<main>'
>> "A" + 1.to_s
=> "A1"
而且,您不需要 Name.to_s
,因为 Name 已经是一个 String 对象。只需 Name
就足够了。
将 Fixnum (length
) 转换为字符串:
puts "My name has " + Name.length.to_s + " characters."
或者,作为替代:
puts "My name has #{Name.length} characters."
关于ruby - 打印 string.length 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18013278/