tags:

views:

79

answers:

3

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#///" 
+9  A: 

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

Trevoke
Ah, that clears it up. A bit of a nuuby here thanks.
Zombies
this wont work for all parameter type, for example arrays or hashes
ennuikiller
ennuikiller: you are right. I just want to illustrate the idea.
Trevoke
This `Changeable` could be a module with only the `change_me!` method. Then, you can `include` it into a class definition or `extend` an individual object.
glenn jackman
@glenn : you are right! But now we just move further and further away from the exact question, and soon we'll be talking about the phase of the moon.. :)
Trevoke
+1  A: 

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
FM
So what I am really asking is how to mutate objects. Rather, write my own method that mutates an object...
Zombies
+1  A: 

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.

hurikhan77
This makes me shiver and reminds me of the bug in COBOL where you could change the value of 1 to be 2.It is quite close to what the OP asked for though :)
Trevoke
@Trevoke luckily Ruby is not affected by this bug, although it would be interesting to generate stuff like 2+2=5 ;-)
hurikhan77