Skip to content

Instantly share code, notes, and snippets.

@pmodin
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmodin/d46ea10e53385daa1442 to your computer and use it in GitHub Desktop.
Save pmodin/d46ea10e53385daa1442 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Ruby Project Night 2014-09-22 @ SUP46, Stockholm
# Why does the to_s methods yeild different results?
# What am I doing wrong and how should I do different?
#
# After a good nights sleep I still cannot wrap my head around this.
#
# ruby -v : ruby 2.0.0p353 (2013-11-22 revision 43784) [x86_64-linux]
# Internal list class
class List
attr_reader :list
def initialize(elem)
@list = Array.new(elem)
end
# method 1
def to_s
@list.to_s
end
# method 2
# def to_s
# @list
# end
end
list = List.new(%w(1 2 3))
puts list # method 1: ["1", "2", "3"]
# method 2: #<List:0x00000002587648>
puts list.list # 1\n2\n3\n <= these are actual newlines in console
@mike-burns
Copy link

Shorter example:

irb(main):023:0> puts %w(1 2 3)
1
2
3
=> nil
irb(main):024:0> puts %w(1 2 3).to_s
["1", "2", "3"]
=> nil
irb(main):025:0> puts %w(1 2 3).inspect
["1", "2", "3"]
=> nil

@mike-burns
Copy link

https://github.com/ruby/ruby/blob/d198d64e0464c141f70c49880bf511ac3dcd1162/io.c#L7097-L7126

If it is enumerable, and the value is a string, then it prints it with a newline.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment