Replacing the to_s method in Ruby. Not printing out desired string

后端 未结 4 1115
甜味超标
甜味超标 2020-12-11 12:05

So, I am just beginning to learn Ruby and I included a to_s method in my Class so that I can simply pass the Object to a puts method and have it return more than just the Ob

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 12:29

    When given arguments that are not strings or arrays puts calls rb_obj_as_string to turn its arguments into strings (see rb_io_puts)

    If you search for rb_obj_as_string through the ruby codebase (I find http://rxr.whitequark.org useful for this) you can see it's defined as

    VALUE rb_obj_as_string(VALUE obj)
    {
      VALUE str;
    
      if (RB_TYPE_P(obj, T_STRING)) {
        return obj;
      }
      str = rb_funcall(obj, id_to_s, 0);
      if (!RB_TYPE_P(str, T_STRING))
        return rb_any_to_s(obj);
      if (OBJ_TAINTED(obj)) OBJ_TAINT(str);
      return str;
    }
    

    In brief this:

    • returns straightaway if the argument is already a string
    • calls to_s
    • if the result is not a string, call rb_any_to_s and return that.

    rb_any_to_s is what implements the default "class name and id" result that you're seeing: for any object it returns a string of the form #

    Returning to your code, when you run puts player1 it calls rb_obj_as_string to convert your player to a string.

    This first calls your to_s method, which uses puts to output your message. Your method then returns nil (because that's what puts always returns) so ruby calls rb_any_to_s, and that is what the outermost puts ends up using.

提交回复
热议问题