Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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#///" 
like image 350
Zombies Avatar asked Feb 15 '10 14:02

Zombies


People also ask

Can we assign a value to parameter?

Assigning a value to a parameter can be done in the following ways: From the command line using the -define along with the appropriate parameter and value. A separate -define option is required for each parameter you want to run.

What is * args in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

What is a parameter in a function call?

A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions.


3 Answers

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..

like image 90
Trevoke Avatar answered Sep 25 '22 23:09

Trevoke


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.

like image 38
hurikhan77 Avatar answered Sep 24 '22 23:09

hurikhan77


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
like image 43
FMc Avatar answered Sep 22 '22 23:09

FMc