Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about_classes.rb inspect and self in ruby

Tags:

ruby

self

inspect

I'm currently working on about_classes.rb. I'm confused on the concept of inspect and how it relates to self. Does calling an object automatically return the inspect method for that object?

class Dog7
    attr_reader :name

    def initialize(initial_name)
      @name = initial_name
    end

    def get_self
      self
    end

    def to_s
      __
    end

    def inspect
      "<Dog named '#{name}'>"
    end
  end

  def test_inside_a_method_self_refers_to_the_containing_object
    fido = Dog7.new("Fido")

    fidos_self = fido.get_self
    assert_equal __, fidos_self
  end

  def test_to_s_provides_a_string_version_of_the_object
    fido = Dog7.new("Fido")
    assert_equal __, fido.to_s
  end

  def test_to_s_is_used_in_string_interpolation
    fido = Dog7.new("Fido")
    assert_equal __, "My dog is #{fido}"
  end

  def test_inspect_provides_a_more_complete_string_version
    fido = Dog7.new("Fido")
    assert_equal __, fido.inspect
  end

  def test_all_objects_support_to_s_and_inspect
    array = [1,2,3]

    assert_equal __, array.to_s
    assert_equal __, array.inspect

    assert_equal __, "STRING".to_s
    assert_equal __, "STRING".inspect
  end
like image 774
Uronacid Avatar asked Mar 09 '26 05:03

Uronacid


1 Answers

self and inspect have no special relationship -- it just so happens that the "Ruby koans" tutorial which you are using teaches you about both at the same time.

self is a keyword which, inside a method, evaluates to the object which you called the method on.

inspect is a method implemented by all objects, which returns a string representation of the object. to_s also returns a string representation of an object.

The difference is that the string returned by inspect will generally, if possible, mimic the Ruby syntax which can create an equivalent object. inspect is generally used for debugging. The string returned by to_s is usually more appropriate for displaying to an end user.

The "#{expression}" syntax implicitly calls to_s on the object which results from evaluating expression.

like image 114
Alex D Avatar answered Mar 11 '26 06:03

Alex D