Ruby 打印string.length时出错
为什么我不能打印常量字符串的长度? 这是我的代码:Ruby 打印string.length时出错,ruby,string,fixnum,Ruby,String,Fixnum,为什么我不能打印常量字符串的长度? 这是我的代码: #!/usr/bin/ruby Name = "Edgar Wallace" name = "123456" puts "Hello, my name is " + Name puts "My name has " + Name.to_s.length + " characters." 我已经读过“”,但不幸的是它对我没有帮助 尝试后,将抛出此错误: ./hello.rb:7:in `+': can't convert Fixnum int
#!/usr/bin/ruby
Name = "Edgar Wallace"
name = "123456"
puts "Hello, my name is " + Name
puts "My name has " + Name.to_s.length + " characters."
我已经读过“”,但不幸的是它对我没有帮助
尝试后,将抛出此错误:
./hello.rb:7:in `+': can't convert Fixnum into String (TypeError)
from ./hello.rb:7:in `<main>'
/hello.rb:7:in`+':无法将Fixnum转换为字符串(TypeError)
from./hello.rb:7:in`'
不能使用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"
或者,作为替代方案:
puts "My name has #{Name.length} characters."
在Ruby中使用插值“#{}”
。它将计算表达式并打印字符串:
#!/usr/bin/ruby
Name = "Edgar Wallace"
name = "123456"
puts "My name has #{Name.length} characters."
注意:如果使用带单引号(')的字符串,则不能使用插值。使用双引号。变量在Ruby中应该是小写的,即
name
而不是name
。这可能是一堂关于如何在惯用Ruby中插入字符串的好课。我相信很多语言都希望人们通过添加子字符串来构建字符串,但ruby绝对不是其中之一。
#!/usr/bin/ruby
Name = "Edgar Wallace"
name = "123456"
puts "My name has #{Name.length} characters."