by wrs · 16y ago · 0 comments
Also, the parentheses are always optional, not just for zero-argument calls, so he also missed the opportunity to discuss "poetry mode Ruby": a bunch of method calls with no parentheses. Stylistically, "poetry mode" enables the pseudo-DSL style that Ruby frameworks use frequently, but can't really be done in Python.
if baz>10:
func = self.foo
else:
func = self.bar
result = func()
Here func gets assigned something called a "bound method", which has a reference to the object and the method, which you can then apply the () operator and call. I am not a rubyist, but my understanding is that you would use a symbol to do a similar thing. if baz > 10
func = :foo
else
func = :bar
end
result = self.send(func) if baz > 10
func = method(:foo)
else
func = method(:bar)
end
result = func.call
Here, we actually deal with the Method objects, rather than just sending a dynamic message. Although the send() approach would be closer to idiomatic Ruby, I wanted to emphasize that dealing with methods as first class objects in Ruby is indeed possible.So, for instance, you might solve it with:
result = case
when baz>10 then foo
else bar
end
This is synthetic, of course. If the goal is to pass around methods, there are lambdas and codeblocks that can be passed around and may fit the problem more naturally than sending yourself a symbol as a message. result = if baz > 10
foo
else
bar
end result = case
when baz>10 then foo
else bar
end
is a translation of if baz>10:
result = self.foo()
else:
result = self.bar()
while result = if baz > 10
foo
else
bar
end
is a translation of result = self.foo() if baz>10 else self.bar()
It's true that some things have to be changed when translating, but you can't ignore the deliberate structure of the original. Let's say I want to look at how inter-sentence objects work in two languages. I give you the phrase: "Raining cats and dogs. This is what the weather is like." You can't translate it as if it said "It's raining cats and dogs" without losing the basis of comparison entirely.