ruby - A way to implement `String#split!` -
ruby - A way to implement `String#split!` -
sometimes need such method, alter class of own object. there string#delete!
, #downcase!
, #encode!
, #gsub!
, #strip!
, #slice!
, etc. trying alter string, resulting class anyway still string
. , want method, can convert string
array
. way create this:
irb(main):082:0> str = "qwerty" => "qwerty" irb(main):083:0> str.split! "e" => ["qw", "rty"] irb(main):084:0> str => ["qw", "rty"]
is possible? maybe cool state of japan kung-fu or ugly bicycles — see solution.
nope, not possible. objects can't alter classes in ruby.
in smalltalk, example, utilize become:
:
becomesubstrings: astring self become: (self substrings: astring).
if phone call this:
s := 'qwerty'. s becomesubstrings: 'e'.
now, s
array:
transcript show: s printstring.
the result is:
#('qw' 'rty')
technically, become:
doesn't alter class of object, rather lets 1 object become object. in case, allow self
become result of self substrings:
, splits string array of substrings. result same: original string receiver array.
ruby class self-modifying
Comments
Post a Comment