Ruby - эквивалент метода Python __str __ ()? - PullRequest
5 голосов
/ 25 сентября 2008

Есть ли в Ruby эквивалент метода __str__(), который вы можете определить в классах Python?

Ответы [ 3 ]

15 голосов
/ 25 сентября 2008

Вы можете использовать to_s.

http://briancarper.net/2006/09/26/ruby-to_s-vs-to_str/

6 голосов
/ 26 сентября 2008

FWIW, осмотреть, вероятно, больше похоже на __repr__(), чем __str__()

из справочника библиотеки ...

repr (self)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required.

4 голосов
/ 25 сентября 2008

В основных классах это обычно «проверка».

Например:

irb(main):001:0> puts "array is: #{[1,2,3].inspect}"
array is: [1, 2, 3]
=> nil
irb(main):002:0> puts "array is: #{[1,2,3]}"
array is: 123
=> nil
irb(main):003:0>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...