Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby version of to String method

Tags:

python

ruby

This question is about formatting ruby's strings.

In Python, built-in data structures have a built-in to-string method, and so when a variable is printed, the string is conveniently formatted to be reflective of the data structure used. For example:

>>>$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
$>>> a = [1,2,3,4]
$>>> str(a)
'[1, 2, 3, 4]'
$>>> print a
[1, 2, 3, 4]
$>>> d = { "a":"a", "b":"b", 1:5 }
$>>> str(d)
"{'a': 'a', 1: 5, 'b': 'b'}"
$>>> print d
{'a': 'a', 1: 5, 'b': 'b'}
$>>> x = [1, 23, 4]
$>>> print x
[1, 23, 4]

notice that when i print a, the value is [1, 2, 3, 4]

However, in ruby, when i try to do the same things, i get this result:

>>>$ irb
irb(main):001:0> x = [1,23,4]
=> [1, 23, 4]
irb(main):002:0> x.to_s
=> "1234"
irb(main):003:0> puts x
1
23
4 
=> nil
irb(main):004:0> print x
1234=> nil
irb(main):005:0> h = { "a" => "a", 1 => 5, 'b'=>'b' } 
=> {"a"=>"a", "b"=>"b", 1=>5}
irb(main):006:0> print h 
aabb15=> nil
irb(main):007:0> h.to_s
=> "aabb15"
irb(main):008:0> puts h
aabb15
=> nil
irb(main):009:0>

As you can see, there is no formatting with the to_s method. Furthermore, there's a uniqueness problem if i call to_s on [1,2,3,4] and [1,23,4] and [1234] because the to_s clumps all elements together so they all end up being "1234". I know that i can try to emulate the python built-in to-string methods for every native data structure by overriding the to_s method ( "[" + a.join(",") + "]" #just for arrays), but i was wondering if there is a better alternative since hacking it would seem to break the convention-over-configuration concept.

So is there a ruby equivalent of python's built-in to-string method?

like image 877
dzt Avatar asked Jun 29 '10 19:06

dzt


1 Answers

[1,23,4].inspect #=> "[1, 23, 4]"
p [1,23,4] # Same as  puts [1,23,4].inspect
like image 105
sepp2k Avatar answered Sep 28 '22 17:09

sepp2k