Ruby: How do I change the value of a parameter in a function call?
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#///"
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..
You want to do this:
def change_me(val)
val.replace "#{val}!"
end
This replaces 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.
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
精彩评论