seki
seki

Reputation: 89

Using 'include?' to check if there is a space in a string

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

Answers (1)

tadman
tadman

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

Related Questions