Question: How does ruby parse 2 /3/ 4 as 2 ÷ 3 ÷ 4?

Question

How does ruby parse 2 /3/ 4 as 2 ÷ 3 ÷ 4?

Answers 1
Added at 2017-01-04 23:01
Tags
Question

A lot of ruby's syntax and parsing is relatively logical, but I am confused as to how ruby knows, from context, that 2 /3/ 4 is 2 ÷ 3 ÷ 4 instead of parsing /3/ as a regex? It's a correct parsing, but /3/ is also a valid regex, and how would it know that /3/ is not a regex.

I thought that this might be a numeric literal thing, but if you do

a = 6
b = 4
c = 2

a /b/ c

Ruby still parses this as division. How does this work?

Actually, I realized there is more to this question,

let's say I have this

def a(x)
  x
end

a = 4
b = 2
i = 4

a /b/i #=> 0

How is a /b/i parsed as 0 instead of /b/i as in why does a /b/i get parsed as a./(b./(i)) instead of a(/b/i)?

Answers to

How does ruby parse 2 /3/ 4 as 2 ÷ 3 ÷ 4?

nr: #1 dodano: 2017-01-04 23:01

In Ruby (and some other languages), operators are actually methods of the objects in your expression. Thus Ruby sees your expression as:

(a./(b))./(c)

When you use regexes there is no leading object so Ruby can figure out that you want a regex and not division.

Here is a nice article for more info.

Source Show
◀ Wstecz