mercredi 5 octobre 2016

confudes between instance variable and local variable in ruby

I recently started learning ruby and i am confused between instance variable and local variable and class variable. so , i recently written code which will find the largest palindrome in 1000 prime numbers. code is:

    def prime_large(number)
    arr_prime = []
    Prime.each(number) do |x|
        new_arr_prime = arr_prime.push(x.to_s)
        updated = new_arr_prime.select { |y| y.reverse == y }
    end
    p updated.max 
end
p prime_large(1000)

error i got is:

undefined local variable or method `updated' for main:Object (NameError)

I know that updated is a local variable of prime so i can't access it outside it but i changed the code by replacing it with @updated as below:

    def prime_large(number)
    arr_prime = []
    Prime.each(number) do |x|
        new_arr_prime = arr_prime.push(x.to_s)
        @updated = new_arr_prime.select { |y| y.reverse == y }
    end
    p @updated.max 
end
p prime_large(1000)

after changing it , i got the output:

"929"
"929"

in my code , without creating a class how my instance variable ( @updated) is working . i am confused between local and instance variable . can anyone please explain me the differences and how they work ?

Aucun commentaire:

Enregistrer un commentaire