search

Home  >  Q&A  >  body text

Ruby中为何要同时有to_s,to_str,inspect这三个函数?nil.inspect为何是“nil”

ruby新手,求大侠指点一二。

怪我咯怪我咯2804 days ago751

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-24 09:11:51

    First question:
    to_s should be a widely existing method, and to_str should be String or a method that only a few classes have. Ruby does have many methods, https://ruby-china.org/topics/25311.

    Second question:
    The return type of inspect is string, which returns a human-readable representation of the current object. nil.inpsect returns "nil" 因为他就是返回 "nil", just look at the NilClass#inspect documentation.

    reply
    0
  • 怪我咯

    怪我咯2017-04-24 09:11:51

    A problem needs to be pointed out here, that is, nil跟其他语言中的null是不一样的,nil in Ruby is an object (not a class, it is an object of the NilClass class). This object is used in Ruby to represent without anything, but it is an object in itself .

    reply
    0
  • Cancelreply