rubyif-statementunless

Using a one-line unless or if statement in Ruby


I am new to Ruby. I am looking for an elegant one line solution to this line of code:

puts "Year: ".colorize(:light_blue) + "#{instrument.year}"

I would like it to print "N/A" if instrument.year is "" (an empty string). I imagine an unless, if or || might work, but so for nothing has quite worked for me. Still learning! I have several fields that need this treatment, so I'd like to avoid an if/else/end statement.

Thanks in advance!


Solution

  • I'm not sure what exactly you want but what I understood is you want to display instrument.year or N/A if instrument.year is an empty string.

    So what I would do is use a ternary:

    puts "Year: ".colorize(:light_blue) + "#{instrument.year.empty? ? 'N/A' : instrument.year}"