【问题标题】:Error when printing string.length打印 string.length 时出错
【发布时间】:2013-08-02 09:23:41
【问题描述】:

为什么我不能打印常量字符串的长度? 这是我的代码:

#!/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>'

【问题讨论】:

  • 变量在 Ruby 中应该是小写的,即name 而不是Name。
  • 这可能是关于如何在惯用的 ruby​​ 中插入字符串的一个很好的课程。我确信有很多语言希望人们通过添加子字符串来构建字符串,但 ruby​​ 绝对不是其中之一。

标签: ruby string fixnum


【解决方案1】:

您不能使用 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."

【讨论】:

    【解决方案2】:

    在 Ruby 中使用插值 "#{}"。它将评估您的表达式并打印您的字符串:

    #!/usr/bin/ruby
    Name = "Edgar Wallace"
    name = "123456"
    
    puts "My name has #{Name.length} characters."
    

    注意:如果您使用带单引号 (') 的字符串,则不能使用插值。使用双引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 2017-09-18
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多