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开发者_StackOverflow中文版 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.
精彩评论