Trying to write a function foo that behaves as follows: foo(x), asks
for input and we give it ‘hello’, function creates a variable called x
and sets equal to ‘hello’. We now have an x variable with a value for
use at later time.
def foo(x)
x = gets.chomp!
return x
end
Now we call x and get “hello”
Not quite sure how to return that variable so that I can access it
later, any help?
i’m not on a machine with ruby installed at the moment, but i don’t see
why this wouldn’t work:
def foo @x = gets.chomp!
end
the ‘return’ statement isn’t necessary, as ruby always returns the
last value evaluated for a given variable. the ‘@’ symbol creates an
instance variable, available anywhere within a class instance. ‘@@’
will give you a class variable, shared across all instances of a class.
‘$’ will give you a global variable, but you probably don’t really want
that - they’re ugly and muck up the works.
sorry if i misunderstood what you wanted to do from your first post…
“…asks for input and we give it ‘hello’, function creates a variable
called x and sets equal to ‘hello’. We now have an x variable with a
value for use at later time.”
as 7stud pointed out, my suggestion doesn’t take an argument, but does
set the “x variable” to an instance variable with the value of the user
input:
def foo @x = gets.chomp!
end
foo
puts @x
hello
=> hello
if you want to give #foo an argument, have that made an instance
variable, and be able to change the “x variable,” you could do something
like this:
def foo(x) @x = x
end
@x = " "
puts @x
input = gets.chomp!
foo(input)
puts @x
foo(“bar”)
puts @x
your last post leads me to think that you don’t want the argument to #foo set to the “x variable,” but that you want the argument itself to
become an instance variable. if that’s the case, then maybe something
like this is what you’re looking for:
input = gets.chomp! #input will have to start with “@”
instance_variable_set(input, “hello”)
or set both the variable and the value from user input:
your last post leads me to think that you don’t want the argument to #foo set to the “x variable,” but that you want the argument itself to
become an instance variable. if that’s the case, then maybe something
like this is what you’re looking for:
input = gets.chomp! #input will have to start with “@”
instance_variable_set(input, “hello”)
or set both the variable and the value from user input:
Sorry for not being clearer. I am looking to pass an argument and have
the function create an instance variable named after the argument passed
in and set to the value that the user inputs.
This works for what I’m looking to do, just not sure if there is a
prettier way of doing it.
def foo(x)
print “Please input value for variable: "
eval(”@#{x} = gets.chomp!")
end