1
\$\begingroup\$

The task is to write a simplified version of Ruby's String#count method oneself. Simplified because it doesn't have to have the negation and sequence parts of the original.

Here my solution:

def custom_count(string, search_char)
    sum = 0
    seg_string = string.split("")
    seg_char = search_char.split("")

    for i in seg_string
        for j in seg_char
            if i == j
                sum += 1
            end
        end
    end

    sum
end

p custom_count("Hello, World!", "l")    # => 3
p custom_count("Hello, World!", "lo")   # => 5
p custom_count("Hello, World!", "le")   # => 4
p custom_count("Hello, World!", "x")    # => 0
p custom_count("Hello, World!", "w")    # => 0
p custom_count("Hello, World!", "W")    # => 1

Is there a better way to solve the task? Perhaps without using nested loops?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

If you can use some ruby String method I would suggest

def custom_count(string, search_char)
  search_char.split("").inject(0) do |count,pattern|
    string.scan(pattern).size + count
  end
end
\$\endgroup\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.