The __repr__
function of python is fancy as it is called when print OBJECT is used automatically.
Is there a ruby equivalence for it? I thought it was to_s, but, I had p OBJECT doesn't seem to call the to_s method.
I got something wrong, p OBJECT seems to call to_s method as follows. I got some hints from my the answers to my other question. - Ruby's to_s method question (from Axe book 2nd edition)
# Sample code from Programing Ruby, page 24
class Song
def to_s
"Song"
end
end
class Songson < Song
def to_s
super + "<Songson>"
end
end
song = Songson.new()
p song
Introduction to the Python __repr__ magic method The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object. In other words, if you pass the returned string of the object_name.
Now if you go by the official python documentation – the __str__ is used to find the “informal”(readable) string representation of an object whereas __repr__ is used to find the “official” string representation of an object.
In order to compare things Ruby has a bunch of comparison operators. The operator == returns true if both objects can be considered the same. For example 1 == 1 * 1 will return true, because the numbers on both sides represent the same value. The expression "A" == "A" also returns true because both strings have the same value.
REPL stands for Read-Eval-Print-Loop. It’s a program that allows you to type Ruby code & see the result directly. One popular REPL is irb.
Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument.
One popular REPL is irb. Another is pry. They’re useful because you can quickly test how some Ruby code works. If you’re trying to convert an array of strings into an array of integers. You may not remember exactly how to do that …
obj.inspect => string
Returns a string containing a human-readable representation of obj
. If not overridden, uses the to_s
method to generate the string.
[ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
Time.new.inspect #=> "Wed Apr 09 08:54:39 CDT 2003"
obj.to_s => string
Returns a string representing obj
. The default to_s
prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘
source
p object uses #inspect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With