I’m new to Ruby.
Is there a way to pass a value by reference to a function in Ruby?
Thanks,
Kevin
Technically everything is by reference. If you directly modify the
variable inside the function it affects the outer variable.
[1] pry(main)> str = ‘a’
=> “a”
[2] pry(main)> def upcase( val )
[2] pry(main)* val.upcase!
[2] pry(main)* end
=> :upcase
[3] pry(main)> upcase str
=> “A”
[4] pry(main)> str
=> “A”
[5] pry(main)>
Joel,
I’m a bit confused. I watched the Learn Ruby in an Hour video. It
showed a numeric forgetting the change outside of the def.
I’m not sure how famous that video is but the rest of it looks accurate.
Thanks,
Kevin
In ruby, everything is an object, and objects are passed by reference.
For performance reasons, there are some exceptions for primitive types.
Small numbers use the machine’s integer types. Also, it would be strange
if you could modify a number: you could make the object 5 represent the
number 6…
Still, the following code shows that even numbers behave like objects
passed by reference in some respects:
def f(x)
puts x.frozen?
end
x=5
y=6
x.freeze
f(x) # => true
f(y) # => false
Also, note that operators such as += affect the variable, not the object
itself:
x = “Hello”
y = x
x << “Hello”
x += " World"
puts x # => HelloHello World
puts y # => HelloHello
Dansei ,
I appreciate you assisting me. I am new to Ruby.
def f(x)
puts x.frozen?
end
x=5
y=6
x.freeze
f(x) # => true
f(y) # => false
I am not sure what the property and question mark are used for at the
end of the x variable.
What is x.frozen and z.freeze?
Thanks,
Kevin
It freezes an object, preventing further modification, see
But all the example is supposed to illustrate is that freeze is a method
that does something to the object and freeze? checks whether it has been
done to the object.
You get the object 5 outside the method and freeze it, then you call the
method, passing the object and check if it has been frozen. In this
respect, even numbers behave like passed-by-reference.
Dansei,
I was looking back on my questions. I forgot to thank you for your time
to explain this.
I have been away from Ruby for a while. I think that I need to take the
intro classes again. I forgot too much of the basics.
Thanks,
Kevin
If you write code on your own in a given language, you will be less
likely to forget.
Robert H.,
Yes I agree. I need to write some of my own code in Ruby.
I go back to looking at it and I forget what I just learned.
Thanks,
Kevin