Use ruby syntactic sugar to print different strings depending on the format of the string
I have a method is_numeric?
which checks if a string is numeric.
I would like to print out the string to the console as part of a sentence, if the string is numeric I would like to surround it in '
marks.
At present I have something like this...
def i_hate_james_blunt_this_much(how_much)
if how_mu开发者_如何转开发ch.is_numeric?
puts "a hate james blunt this much : '" + string + "'\n"
else
puts "a hate james blunt this much : " + string + "\n"
end
end
but I am sure ruby has some syntactic sugar to make it look sweeter, anyone?
How about:
output_string = "a hate james blunt this much : "
output_string += how_much.is_numeris? ? "'#{string}'" : string
Another variant:
hate = how_much.is_numeric? ? "'#{how_much}'" : how_much
puts "i hate james blunt this much : #{hate}\n"
q = how_much.is_numeric?? "'" : ""
And then
puts "a hate james blunt this much : %s%s%s" % [q, how_much, q]
or
puts "a hate james blunt this much : " + q + how_much + q
精彩评论