However, I'm also quickly being won over to the very disciplined approach to programming that the RESOLVE-C++ discipline brings to the table. I'm not ready to make the full-fledged jump to C++ just yet, but it would be very nice to add some of the concepts that make that discipline very efficient into Ruby.
One thing I hate about Ruby is that it doesn't support pass by reference. For example:
def foo(bar)
bar += 1
end
Returns the value of bar + 1, as expected. However, outside of that block, bar still equals it's initial value, since Ruby has just copied the value into the subroutine, executed, and then returned it.
However, if we write it like this:
def foo(bar)
bar += 1
binding
end
Then we have a method that returns a set of bindings... fundamentally useless, until we pair it with the eval command:
mybar = 1
mybar = eval("bar", foo(mybar))
mybar.should == 2
We're basically asking the interpreter to return the value of R in the context of foo(mybar)... which as we discussed, now returns a set of bindings. So, instead of bar being a variable out of scope, it's right there as the value of the parameter mybar + 1.
If you want to implement a method that uses this hacked pass-by-reference, you can just return bindings. But, if you wanted to only have this functionality some of the time, you can just copy the code to a new method of similar name with an appended _binds that returns the bindings.
No comments:
Post a Comment