简体   繁体   中英

how to pass strings to functions not by ref (Ruby)

Check following code

def wipe_mutterings_from( sentence )
   while sentence.include? '('
     open = sentence.index( '(' )
     close = sentence.index( ')', open )
     sentence[open..close] = '' if close
   end
end

foo='abbba (jjjj) kkkkkk'
wipe_mutterings_from( foo )
p foo

In my understanding I have passed the string by ref to the function (much like is done in lower level languages like c/cpp).
Is it possible to pass the string only by value (like in PHP)?
I am fully aware I can duplicate the string inside the function and work only on the copy.

No, everything is passed by reference in Ruby, and strings are mutable. The common thing to do is to dup the string the first thing in the method, as you mention.

However, a much easier way is to simply not do sentence[open..close] but instead something like sentence[0...open] + sentence[(close + 1)..-1] which creates a new string for each iteration. That way you wouldn't have to worry about mutating the string. On the other hand, that solution would create many more string objects, which degrades performance because the garbage collector has to do much more work, but that is only relevant if you do this tens of thousands of times.

Or you could try a more "rubyish" way(eliminating while loops and index calculations):

foo = 'abbba (jjjj) kkkkkk'
p foo.sub(/\(.*\) /, '')

You can try to send just a copy of this string

foo='abbba (jjjj) kkkkkk'
wipe_mutterings_from( foo.clone )
p foo

I can't see any reason why you wouldn't create the new string in the function, and return it. It reads much better and would have less surprises:

foo='abbba (jjjj) kkkkkk'
new_foo = wipe_mutterings_from( foo )
p new_foo

or even

foo='abbba (jjjj) kkkkkk'
foo = wipe_mutterings_from( foo )
p foo

I'd prefer the latter, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM