-1

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!

BTL
  • 4,311
  • 3
  • 24
  • 29
mlgvla
  • 17
  • 3
  • 3
    Why "elegant one line"? That's an artificial constraint; A single line can result in a very convoluted solution that is harder to maintain. – the Tin Man Apr 17 '20 at 00:03
  • Please post a complete working example. It's hard to refactor code when the code is lacking context or isn't executable. – Todd A. Jacobs Apr 17 '20 at 22:34

1 Answers1

0

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}"
BTL
  • 4,311
  • 3
  • 24
  • 29
  • 1
    Yes! I finally did something like you suggested. It turned out that some fields were either empty strings or NILs, so I needed an || in there to account for that. But it works and is the least cluttered solution for the code! Thx! – mlgvla Apr 17 '20 at 23:08