AnswerBun.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!

Related Questions

Google Maps marker management for games

1  Asked on October 27, 2021 by joeyboy

       

Check if array has the same number of even and odd values in Python

11  Asked on February 26, 2021 by uncalled-astronomer

   

Transpose of a matrix using Python 3.8

2  Asked on February 25, 2021

   

Angular Typescript Async queue service

0  Asked on February 22, 2021 by leonel-franchelli

         

A simple terminal-based trading game in C

2  Asked on February 20, 2021 by redwolf-programs

   

Python wrapper for official Hacker News API

1  Asked on February 15, 2021

         

Implementing a Directed and Undirected Graph in Java

1  Asked on February 14, 2021 by msmilkshake

   

c++ shell for linux

2  Asked on February 14, 2021 by the-masked-rebel

     

Excel blank row inserter

2  Asked on February 12, 2021 by sandro4912

       

Private VBA Class Initializer called from Factory #2

0  Asked on February 8, 2021 by cristian-buse

     

Perl – Splitting a string

3  Asked on February 7, 2021 by linny

     

Hackerrank’s Queen’s Attack II

2  Asked on February 6, 2021 by bork

     

C++17 thread pool

2  Asked on February 6, 2021 by osuka_

         

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP