Sanjay Salunkhe
Sanjay Salunkhe

Reputation: 2735

Ruby: Not able to access method of one module from another module

I am learning ruby. for learning purpose i have written a code with nested modules as show below. my task is to print oupupt "IN FIRST A" from module C. i tried Object::A::A.show and ::A::A.show but it is printing output "in second A". i also tried A::A.show but it is giving error as uninitialized constant. please help in understanding why it is printing "in second A" and what i need to do to printer "IN FIRST A" output

module A

  def self.show
    puts "in outer A"
  end

  module A
    def self.show
        puts "IN FIRST A"
    end
  end

  module A
    def self.show
        puts "in second A"
    end
  end

  module C

    def self.show
       puts "in Third A"
    end
    Object::A::A.show
  end

end

Upvotes: 1

Views: 136

Answers (1)

Amadan
Amadan

Reputation: 198324

Consider this example (which is completely analogous):

a = 3
b = 4
b = 5
puts b
# 5

How do I display 4?

Your first method is ::A::show. Your second and third are both ::A::A::show. Thus, your third definition is overwriting your second one, and you only have two methods. The method that prints "IN FIRST A", thus, does not exist after the third def has run. The only way to execute that method is to run it in between the second and third definition, when it's defined but not overwritten yet.

(::A::A::show can also be written ::A::A.show, as you did, with no change in meaning.)

Upvotes: 7

Related Questions