MKB MKB - 2 years ago 71
Ruby Question

What is the usage of super keyword in this given controller?

I am new Ruby on Rails programmer, got stuck into a problem where I have a piece of code

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

I am unable to figure out from where the super keyword is getting value. Tell me if you need anything else to know about. Because I am also new here. Thanks in advance :)

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