--------------090506010402050200010902
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit
Tookelso wrote:
> Hello,
Moin!
> When you pass an argument to a method, is it passed by reference, or by
> value?
> Or, does it depend on the object's type?
>
> For example, in the simple script below, the program outputs "0".
> #-----------------------------------
> def test(c_count)
> c_count _count + 1
> end
> # begin program
> c_count
> test(c_count)
> puts c_count
> #-----------------------------------
> I realize that for simple things, it's better to return a value from
> the method, but I would like to know *why* it's not modifying my
> "c_count" value.
Arguments in Ruby are just objects that are passed via ref because it
would not make much sense to get copies of your Objects all over the
place. It's simpler to just request a copy of an Object if you need one.
(Via Object#clone or #dup)
But note that variables are no Objects, they are just names for Objects!
So how do you accomplish the above? If you just want to return multiple
values use something like this:
def wc(text)
lines ext.count "\n"
words ext.scan(/\S+/).size
bytes ext.size
return [lines, words, bytes]
end
lines, words, bytes c("hello world")
If you really want to do an assignment to a variable after the fact use
something like this:
def inc_score(amount , &block)
block.call(amount)
end
score
score_assign ambda { |new_score| score ew_score }
inc_score(5, &score_assign)
This uses blocks as a callback for doing the assignment.
If you really want boxed Variables (that can be handled as Objects) you
can use the library I attached to do something like this:
def inc(var)
var.value +
end
x
5.times { inc Variable[:x] }
Variable[:x].value # 6
x # 6
--------------090506010402050200010902
Content-Type: application/x-ruby;
name ariable.rb"
Content-Transfer-Encoding: base64
Content-Disposition: inline;
filename ariable.rb"
cmVxdWlyZSAnYmluZGluZ19vZl9jYWxsZXInDQoNCmNsYXNzIFZhcmlhYmxlDQogIGRlZiBz
ZWxmLm5ldyhuYW1lLCBjb250ZXh0ID0gbmlsKQ0KICAgIHJldHVybiBzdXBlcihuYW1lLCBj
b250ZXh0KSB1bmxlc3MgY29udGV4dC5uaWw/DQogICAgQmluZGluZy5vZl9jYWxsZXIgZG8g
fGNvbnRleHR8DQogICAgICBzdXBlcihuYW1lLCBjb250ZXh0KQ0KICAgIGVuZA0KICBlbmQN
CiAgY2xhc3MgPDwgc2VsZjsgYWxpYXMgOltd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