MKB MKB - 1 year ago 89
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

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

Answer Source

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


The above code can be re-written as

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download