From: tamouse mailing lists Date: 2012-12-16T12:16:06+09:00 Subject: Re: Ruby quick reference arranged in ASCII sequence? On Sat, Dec 15, 2012 at 7:32 PM, 7stud -- wrote: > tamouse mailing lists wrote in post #1089227: >> On Sat, Dec 15, 2012 at 9:26 AM, Eric Christopherson >> >> Now, that will all work. But it isn't idiomatic ruby. >> >> print last_name.empty ? "," : "\"#{last_name}\"," >> >> makes better use of ruby's expressiveness. >> > > You forgot a question mark there: > >> print last_name.empty? ? "," : "\"#{last_name}\"," Yup. This is one of the things a second pair of eyes is great for as well. Typing just off the top of my head. If I'd done it in irb, the syntax would have blown and I'd have noticed it. It's the tough ones that second eyes helps on a lot. > Personally, I would never write a ternary operator that was so > confusing. Terseness should never be favored over clarity. And Ruby > has four different quoting mechanisms for strings, so resorting to > escaping quote marks inside strings isn't necessary. > > > last_name = "Smith" > comma = "," > quoted_last_name = %Q{"#{last_name}"} > > puts last_name.empty? ? comma : quoted_last_name > I always seem to forget about the % quote operators, even though I'm used to the similar thing in perl. Someone was recently asking "why would you use them" and here is the perfect example. Given the OP's code had a comma at the end wondering if there's an even better way. Assuming a situation where output is accumulating via printf statements in the OP code, no line terminator (as puts will include), say collecting a set of names to print in a line, separated by commas, say from a hash for lack of better choice at the moment: starring = [{:first_name => 'Sammy', :last_name => 'Hagar'}, {:first_name => 'Billy', :last_name => 'The Kid'}, {:first_name => 'Madonna', :last_name => ''}, {:first_name => 'Bono', :last_name => ''}] # => [{:first_name=>"Sammy", :last_name=>"Hagar"}, {:first_name=>"Billy", :last_name=>"The Kid"}, {:first_name=>"Madonna", :last_name=>""}, {:first_name=>"Bono", :last_name=>""}] starring.collect{|star| %Q{#{person[:first_name]}#{person[:last_name].empty? ? '' : %Q{ "#{person[:last_name]}"}}}}.join(', ') # => "Sammy \"Hagar\", Billy \"The Kid\", Madonna, Bono" when printed, yields: Sammy "Hagar", Billy "The Kid", Madonna, Bono making it a list with/without the oxford comma is for another day.