the12
the12

Reputation: 2415

How can Ruby tell the difference between variables and method names if they have the same scope?

How can Ruby tell the difference between variables and methods if both have the same name and the same scope?

Given the scenario:

def something 
"33"
end

something = "44"

something # --> calling something (variable or method?)

I am confused because both are called with something. My question is two part:

A) Which would win out: variable or method and why?

B) Is there some way for Ruby to distinguish between the two so you can call something (the variable) and something (the method)?

Upvotes: 0

Views: 949

Answers (1)

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

variable would be first, but you can call method:

def foo
   33
end

foo = 44

>foo
#=> 44
>foo() #also you can call it by: self.foo || My omission, thanks @CarySwoveland

#=> 33

On question

why?

@SergioTulentsev gave a good answer:

local variable has priority over bracketless method call because otherwise it wouldn't be possible to refer to the variable

Also, for more information about methods and variables you can read here

Upvotes: 4

Related Questions