clearing a parameter in Ruby?

  • Thread starter Roy Patrick Tan
  • Start date
R

Roy Patrick Tan

Hi,

is it possible to write a method that can "clear" a parameter in Ruby?
That is can a write a method "push" such that for the code below:

x = "Hello"
string_stack.push(x)
puts x

the output will be nil instead of "Hello"?
 
H

Hal E. Fulton

----- Original Message -----
From: "Roy Patrick Tan" <[email protected]>
Newsgroups: comp.lang.ruby
To: "ruby-talk ML" <[email protected]>
Sent: Monday, August 04, 2003 12:36 PM
Subject: clearing a parameter in Ruby?

Hi,

is it possible to write a method that can "clear" a parameter in Ruby?
That is can a write a method "push" such that for the code below:

x = "Hello"
string_stack.push(x)
puts x

the output will be nil instead of "Hello"?

Short answer is no.

Long answer is: If your parameter is something like
a String or an Array, you could do a 'replace' on
its contents. Likewise if it's any complex object
whose state can change, you can change its state.

However, assignment works on variables, not objects.
In general it's impossible to write a method that
knows the name of the variable passed to it, and
so it's impossible to assign to the variable that
was passed into the method. You can manipulate the
object, but not the variable.

HTH,
Hal
 
J

Jim Weirich

Hi,

is it possible to write a method that can "clear" a parameter in Ruby?
That is can a write a method "push" such that for the code below:

x = "Hello"
string_stack.push(x)
puts x

the output will be nil instead of "Hello"?

I don't recommend this (because I think I would get really annoyed if I
were using a library that did this).

But with the above disclaimer, you could do it this way:

class Pusher
def initialize
@stack = Array.new
end

def push(&block)
sym = block.call
@stack.push(eval(sym.to_s, block))
eval "#{sym.to_s} = nil", block
end
end

s = Pusher.new
x = "HI"
s.push { :x }
p x # => nil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top