开发者

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

开发者 https://www.devze.com 2022-12-20 09:30 出处:网络
How would I impelement a function, in ruby, such as the following? change_me! (val) update: What I set out to do was this:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号