DEV Community

Discussion on: Daily Challenge #29 - Xs and Os

Collapse
 
scrabill profile image
Shannon Crabill • Edited

Not a pretty solution, but it seems to work in Ruby

def gossip_girl(string)
  new_string = string.downcase

  if new_string.include?("x") == false && new_string.include?("o") == false
    true
  elsif new_string.include?("x") == true && new_string.include?("o") == true
    x_count = new_string.count("x")
    o_count = new_string.count("o")

    if x_count == o_count
      true
    else
      false
    end
  else
    false
  end
end

Returns

gossip_girl("ooxx") => true 
gossip_girl("xooxx") => false 
gossip_girl("ooxXm") => true 
gossip_girl("zpzpzpp") => true 
gossip_girl("zzoo") => false 
Collapse
 
scrabill profile image
Shannon Crabill • Edited

WAIT. Here's a much cleaner solution in Ruby.

def gossip_girl(string)
  string.downcase.count("x") == string.downcase.count("o")
end

Which returns

gossip_girl("ooxx") => true 
gossip_girl("xooxx") => false 
gossip_girl("ooxXm") => true 
gossip_girl("zpzpzpp") => true 
gossip_girl("zzoo") => false 

This is why you refactor!

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

Very nice! I love your choice of method name 😂 And it's great that you went back to refactor once you realized there were optimizations you could make. No matter what "stakeholders" say about features driving revenue, any developer worth their salt knows that a clean codebase drives features. 👍👍🙌

Thread Thread
 
scrabill profile image
Shannon Crabill

Thanks. I can't think of X's and O's without Gossip Girl.

Clean codebases are so much easier to work with. Not to mention, cost and performance savings.

Collapse
 
databasesponge profile image
MetaDave 🇪🇺

It turns out that you could avoid the #downcase with string.count("xX") == string.count("oO")

I don't know whether the performance would be significantly different, though it would avoid creating a couple of extra string instances.

There are some other interesting variations for #count, such as using it to count lower case letters with "abGvf".count("a-z")