class Klass
attr_accessor :keys
def change_keys(opt)
if opt == 1
keys = [keys[0], keys[keys.length - 1]]
else
tmp = keys[0]
keys[0] = keys[keys.length-1]
keys[keys.length-1] = tmp
end
keys
end
end
klass = Klass.new
klass.keys = [1,2,3,4,5]
# puts klass.change_keys(1)
# puts klass.change_keys(2)
This is not working at all, the error says: undefined method ‘[]’ method for nil:NilClass
Ruby interprets
keys[0]and the others in line 5 as local variables because it has seen akeys = .... There is an ambiguity in Ruby grammar when it comes to differentiate local variables from method calls without arguments that gets disambiguated by that heuristic. that is, if the parser sees an assignment to that identifier then is a local variable if not is a method call.You can solve this by referring to self.keys instead. to make clear that you want to use the accessor method.