The implementation method of `String # split!`

Sometimes I need a method that can change the class of its own object. There are String#delete!, #downcase!, #encode!, #gsub!, #strip!, #slice!, etc. They all try to change the line, but the resulting class is all the same String. And I need a method that can convert Stringto Array. How to do it:

irb(main):082:0> str = "qwerty"
=> "qwerty"
irb(main):083:0> str.split! "e"
=> ["qw", "rty"]
irb(main):084:0> str
=> ["qw", "rty"]

Is it possible? Maybe some cool Japanese kung fu or ugly bikes - I would love to see any solution.

+3
source share
3 answers

No, It is Immpossible. Objects cannot change their classes in Ruby.

In Smalltalk, for example, you can use become::

becomeSubStrings: aString
    self become: (self subStrings: aString).

If you call it like this:

s := 'qwerty'.
s becomeSubStrings: 'e'.

s :

Transcript show: s printString.

:

#('qw' 'rty')

, become: , . self self subStrings:, . : .

+10

Jörg W Mittag . Ruby , .

, , , , :

irb(main):082:0> str = "qwerty"
=> "qwerty"
irb(main):083:0> str = str.split "e"
=> ["qw", "rty"]
irb(main):084:0> str
=> ["qw", "rty"]
0

evil-ruby ( , , - ). , Ruby , , , , , segfaults Ruby-, . .

( BlankSlate + Forwardable).

, . , .

0

Source: https://habr.com/ru/post/1766514/


All Articles