What is wrong with this change_keys function?

I believe I messed up some concepts here, but what is it?

class Klass
attr_accessor :keys

def change_keys
keys = [keys[0], keys[keys.length-1]]
## this works
# res = [keys[0], keys[keys.length-1]]
# keys = res
end
end

klass = Klass.new
klass.keys = [1,2,3]
puts klass.change_keys

… undefined method ‘[]’ on nil:Nil:Class …

webber han wrote in post #1048131:

I believe I messed up some concepts here, but what is it?

class Klass
attr_accessor :keys

def change_keys
keys = [keys[0], keys[keys.length-1]]
## this works
# res = [keys[0], keys[keys.length-1]]
# keys = res
end
end

klass = Klass.new
klass.keys = [1,2,3]
puts klass.change_keys

… undefined method ‘[]’ on nil:Nil:Class …

In fact, I should add self before keys so that becomes:

self.keys = [keys[0], keys[keys.length-1]]

this is critical, since otherwise the Ruby interpreter will take ‘keys’
as an local variable, but what is intended is ‘keys=’ setter method,
from attr_accessor :keys.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs