[Ruby] Определение "+" и перестановка слагаемых

Yuri Leikind YuriLeikind at scnsoft.com
Wed Oct 2 16:59:21 MSD 2002


On Wed, 02 Oct 2002 16:50:50 +0400
Anton Farygin <rider at altlinux.com> wrote:

> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> Yuri Leikind wrote:
> 
> |On Wed, 2 Oct 2002 08:56:33 +0300
> |Ilya Palagin <tux at fioc.kz> wrote:
> |
> |>Здравствуйте,
> |>
> |>К письму приложен файл с кодом. Интересно было бы узнать, как и где
> |>определить метод "+", чтобы скрипт работал с 33-й строкой, т.е. при
> |>перестановке слагаемых?
> |>
> |
> |Может я не все понял, но если не хочется писать каждый раз
> |
> |   cgi.h1{"Some text"} + te.to_s
> |
> |а хочется писать
> |
> |   cgi.h1{"Some text"} + te
> |
> |то можно залезть в класс String и воспользоваться alias_method:
> |
> |class String
> |
> |   alias_method :new_plus_name,  :+
> |   
> |   def+(e) # это у нас расширенный метод +
> |      if e.class == PageElement
> |         self.new_plus_name e.to_s  # но оригинальный метод
> |                                    # сохранился с именем new_plus_name
> |      else
> |         self.new_plus_name e
> |      end
> |   end
> |end
> |
> |Вот. Так будет работать. Я правильно понял, это то, что нужно?
> |
> так тоже будет работать.
> 
> Но можно было просто переименовать в PageElement метод to_s в метод
> to_str. И все работает.
> 
> Единственное НО: это решение я подсмотрел в исходниках Ruby и не знаю,
> документированно ли оно ;-)
> 

Задокументовано:
leikind at leikind,~ >ri to_str
---------------------------------------------------------- String#to_str
     str.to_str -> str
------------------------------------------------------------------------
     Synonym for String#to_s. to_str is used by methods such as
     String#concat to convert their arguments to a string. Unlike to_s,
     which is supported by almost all classes, to_str is normally
     implemented only by those classes that act like strings. Of the
     built-in classes, only Exception and String implement to_str.

leikind at leikind,~ >

String#concat  это и есть наш плюс. Да, так элегантнее,
достаточно только добавить одну строку в класс PageElement

   alias :to_str, :to_s


___
Best regards,
Yuri Leikind


I invented the term Object-Oriented, and
I can tell you I did not have C++ in mind.
Alan Kay



More information about the Ruby mailing list