TransWikia.com

Custom include? method for a substring

Code Review Asked by michael.zech on December 23, 2020

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?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP