MKB MKB - 5 months ago 9
Ruby Question

What is the usage of super keyword here?

I have a piece of code

def data
data_type == 'option' ? options[super.to_i] : super
end


I cannot figure out from where the super keyword is getting the value.

Answer

Here super keyword calls the same data method of its parent class if data_type == 'option' is false. Check this link for a detailed explanation. Super keyword in Ruby

Update:

The above code can be re-written as

if data_type == 'option'
  options[super.to_i]#options is probably a hash/array here.
else
  super
end

When we call super it returns a value after executing it's parent class's data method, lets assume it returned "5", we're converting that to an integer and getting data out of options array. i.e., options[5].

In the else block we're simply returning the the value parent's data method got us.

Comments