Reputation: 89
I am testing whether a name @fm1
has a space (because dog does not have a surname).
def family_member?
if @fm1.include?(" ")
puts @fm1.split(/ |\_|\-/).map(&:capitalize).join(" ") + " is a puppy!"
elsif @fm1.include?("schnider")
puts @fm1.split(/ |\_|\-/).map(&:capitalize).join(" ") + " is Schnider's member."
else
puts @fm1.split(/ |\_|\-/).map(&:capitalize).join(" ") + " is a guest."
end
end
When I do if @fm1.include?(" ")
, it shows the result after else
. I would like to know if there is any method. Can you help me finish this?
Upvotes: 1
Views: 92
Reputation: 211610
The most Ruby way to do this is with case
and regular expressions:
def family_member_text
name = @fm1.split(/ |\_|\-/).map(&:capitalize).join(" ")
case (@fm1)
when /\s/
"#{name} is a puppy!"
when /schnider/i
"#{name} is Schnider's member."
else
"#{name} is a guest."
end
end
Where this method returns text that you can, but are not obligated to feed to puts
, something that leads to more modular code design. Remember your SOLID principles.
Note that I've also applied DRY (Don't Repeat Yourself) here to clean up the duplicated name canonicalization code. That's also probably wrong because names like "Leonardo da Vinci" do not have a capital "Da".
Upvotes: 1