Ruby on Rails
Wednesday, December 26, 2012
On Tuesday, 25 December 2012 20:13:16 UTC-5, John Merlino wrote:
ok, it didn't look like nested methods. But I made to believe that
this:
sum<=square*deviation|a
is exactly the same as this:
sum<=(square*(deviation|(a)))
So if this is true, then still a question remains.
That's not how it parses, thanks to operator precedence - the same reason that 2+5*10+3 parses as 2.+((5.*(10)).+(3)) and not 2.+(5.*(10.+(3))).
You can use a tool like Ripper (http://www.rubyinside.com/using-ripper-to-see-how-ruby-is-parsing-your-code-5270.html) to see exactly how something is being parsed. Trying your expression yields:
[:program,
[[:binary,
[:vcall, [:@ident, "sum", [1, 0]]],
:<=,
[:binary,
[:binary,
[:vcall, [:@ident, "square", [1, 5]]],
:*,
[:vcall, [:@ident, "deviation", [1, 12]]]],
:|,
[:vcall, [:@ident, "a", [1, 22]]]]]]]
Or, distilled back to a fully-parenthized code version:
sum <= ((square*deviation) | a)
With the method calls written out explicitly:
sum.<=((square.*(deviation)).|(a))
Essentially, this creates a function that calculates the squared deviation from the mean (square*deviation), applies it to the list a, and then sums the resulting values.
This sort of confusion is why most people recommend avoiding operator overloading in most cases - there are a bunch of precedence rules built into the language, and you're essentially stuck with them.
--Matt Jones
-- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/i8Zt0_c0fRsJ.
For more options, visit https://groups.google.com/groups/opt_out.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment