Skip to content

Instantly share code, notes, and snippets.

@dharshan
Last active Nov 29, 2017
Embed
What would you like to do?
Substring in String in Ruby using each loop
1
Enter a String
bengaluru
Enter a Sub String
uru
=> Present
2
Enter a String
bengaluru
Enter a Sub String
ban
=> NOT Present
3
Enter a String
bengaluru at 9am
Enter a Sub String
at 9
=> Present
4
Enter a String
Enter a Sub String
at
=> Not Present
p 'Enter String'
string = gets.chomp
p 'Enter Sub String'
sub_string = gets.chomp
def sub_string_present?(string, sub_string)
str_ar = string.split('')
sub_str_ar = sub_string.split('')
i = 0
str_ar.each do |str|
j = 0
sub_str_ar.each do |sstr|
if str_ar[i + j] == sub_str_ar[j]
if j == (sub_str_ar.count - 1)
return true
end
j += 1
else
break
end
end
i += 1
end
return false
end
if sub_string_present?(string, sub_string)
p 'Present'
else
p 'Not Present'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment