Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53607

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.

Upvotes: 1

Views: 2760

Answers (4)

Theo
Theo

Reputation: 132922

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.

Upvotes: 3

seph
seph

Reputation: 6076

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

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

Upvotes: 1

EdvardM
EdvardM

Reputation: 3082

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.

Upvotes: 0

fl00r
fl00r

Reputation: 83680

You can try to send just a copy of this string

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

Upvotes: 0

Related Questions