DEV Community

Discussion on: Binary Gap of a Number

Collapse
 
baweaver profile image
Brandon Weaver

Enumerable in Ruby has a lot of handy methods you may enjoy. In this case we'll want String#chars, Enumerable#slice_when, Enumerable#max_by, and Array#size:

def binary_gap(string)
  string
    .chars
    .slice_when { |a, b| a != b }
    .max_by { |s| s[0] == '0' ? s.size : 0 }
    .size
end

Now commenting that out to explain what's going on:

def binary_gap(string)
  string
    # Get the characters of a string
    .chars
    # Slice them into groups when the next character isn't equal to the previous one
    .slice_when { |a, b| a != b }
    # Find the biggest group, but only if it's a group of 0s, return 0 for 1 to make it lesser
    .max_by { |s| s[0] == '0' ? s.size : 0 }
    # Then finally get the size of that largest group
    .size
end

each_char could probably be used here as well.

Collapse
 
sureshpathipati profile image
Pathipati Suresh Kumar

Agree!. Looks even better and understandable