Tutorial :Ruby: How do I change the value of a parameter in a function call?



Question:

How would I impelement a function, in ruby, such as the following?

change_me! (val)  

update:

What I set out to do was this:

def change_me! (val)    val = val.chop while val.end_with? '#' or val.end_with? '/'  end  

This just ended up with....

change_me! 'test#///'     => "test#///"   


Solution:1

You're thinking about this the wrong way around. While it may be possible to do this in Ruby, it would be overly complicated. The proper way to do this would be:

val.change_me!  

Which, of course, varies depending on the class of what you want to change. The point is that, by convention, the methods with '!' affect the class instance on which they're called. So...

class Changeable    def initialize var      @var = var    end      def change_me! change=1      @var += change    end  end    a = Changeable.new 5 # => New object "Changeable", value 5  a.change_me! 6 # => @var = 7  a.change_me! # => @var = 8  

Hope this helps a bit..


Solution:2

You want to do this:

def change_me(val)    val.replace "#{val}!"  end  

This replace the value with a new one. But trust me: You don't usually want to design your ruby code in such a way. Start thinking in objects and classes. Design your code free of side-effects. It will save a whole lot of trouble.


Solution:3

What kind of object is val and how do you want to change it? If you just want to mutate an object (say, an array or a string), what you are asking for works directly:

def change_me!(me)      me << 'abides'  end     val = %w(the dude)  change_me!(val)  puts val.inspect    val = "the dude "  change_me!(val)  puts val.inspect  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »