Confused between instance variable and local variable

I recently started learning ruby ​​and am confused between an instance variable and a local variable and a class variable. therefore, I recently wrote code that finds the largest palindrome in 1000 primes. the code:

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)

The error I received is:

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

I know that the updated local variable is prime, so I cannot access it outside of it, but I changed the code, replacing it with @updated, as shown 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 result:

"929"
"929"

in my code, without creating a class, how my instance variable (@updated) works. I am confused between local and instance variable. can someone explain the differences to me and how they work?

+4
1

updated, , . , Prime.each(number) do end.

@updated.

, (@updated)

, Ruby - . , main.

, , , main.

, , , updated Prime.each(number) do end:

def prime_large(number)
  arr_prime = []
  updated   = nil # initialize local varialbe
  Prime.each(number) do |x|
    new_arr_prime = arr_prime.push(x.to_s)
    updated = new_arr_prime.select { |y| y.reverse == y } # assign new value
  end
  p updated.max 
end
p prime_large(1000)

, irb pry :

self               # the object in the context of which you are currently
#=> main
self.class         # main is an instance of class Object, any methods defined
                   # within main are added to Object class as instance methods
#=> Object
instance_variables # list of it instance variables, none yet created
#=> []
@variable = 1      # create and instance variable
#=> 1
instance_variables # now created variable occurs in the list of current object instance variables
#=> [:@variable]
def hello; :hello end # define method
#=> :hello
self.class.public_instance_methods(false) # list instance methods defined in Object
#=> [:hello]

Ruby.

+5

Source: https://habr.com/ru/post/1656859/


All Articles