AsapCancel
AsapCancel

Reputation: 87

Accessing variable from another method within the same class

I am trying to access variable b from "countX" method in "printX" method, but it always gives error, like the variable doesnt have scope for it. I kinda can see myself whats the problem, but dont really know how to go around this. I just want to be able to access my variable b from second method, and i guess it has to do something with how I name it in the previous method. The error given is: undefined local variable or method `b'.. Off topic, I know this is way easier to be done within the same method, but I am trying to practise a bit this way so even if its not the best way, I'd like to have it done

class Countin
    def initialize(text)
        @text = text

        def countX
            a = @text.split(/\W+/)          
            b = Hash.new(0)
            a.each do |v|
                b[v] += 1
            end
        end

        def printX
            b.each do |k, v|
                puts "#{k} appears #{v} times"
            end
        end
    end
end

Upvotes: 2

Views: 4359

Answers (1)

Horacio
Horacio

Reputation: 2965

You'll need to create an object variable

    class Countin
        def initialize(text)
            @text = text

            def countX
                a = @text.split(/\W+/)          
                @b = Hash.new(0)
                a.each do |v|
                    @b[v] += 1
                end
            end

            def printX
                @b.each do |k, v|
                    puts "#{k} appears #{v} times"
                end
            end
        end 
end

Upvotes: 4

Related Questions