1
\$\begingroup\$

Task:

Write a function which returns true if a given substring is found within a given string. If the substring isn't found, then return false.

My implementation:

#!/usr/bin/env ruby
def custom_include?(string, substring)
    len = substring.size
    last_feasible = string.size - len
    
    for i in 0..last_feasible
        current_slice = string[i...i + len]

        if current_slice == substring
            return true
        end
    end 

    false
end

puts custom_include? "The Ruby Programming Language is amazing!", "Language" # true
puts custom_include? "The Ruby Programming Language is amazing!", "language" # false
puts custom_include? "The Ruby Programming Language is amazing!", "amazing!" # true
puts custom_include? "The Ruby Programming Language is amazing!", "The"      # true 
puts custom_include? "The Ruby Programming Language is amazing!", "Test"     # false

Is there a way to avoid the for-loop? Should I try to "save" variables?

Using variables make it easier for me to development a solution for such an exercise. Moreover I think it makes the script for readable and understandable. What's your opinion about that approach?

\$\endgroup\$
2
  • \$\begingroup\$ You could just do def custom_include?(string, substring) string.include?(substring) end. Nothing in the task prevents this and it sounds like they just want it as a function instead of a method. \$\endgroup\$ – superb rain Aug 9 '20 at 6:22
  • \$\begingroup\$ I would definitely add a test case where the substring is longer than the string. \$\endgroup\$ – D. SM Aug 17 '20 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.