I learned Rails and now would like to expand my knowledge of Ruby. So I'm doing some C++ exercises in Ruby. Specifically I need to find if a substring exists in a string. If it does I need it to return its starting index. If it doesn't exist have it return -1. I came up with a Ruby solution that's very similar to C++ and was wondering if there's a "better", more idiomatic solution in Ruby?
C++
int find(char str[], char sub_str[])
{
int str_length = strlen(str);
int sub_str_length = strlen(sub_str);
bool match = false;
for(int i=0; i<str_length; i++)
{
if(str[i] == sub_str[0])
{
for(int j=1; j<sub_str_length; j++)
{
if(str[i+j] == sub_str[j])
match = true;
else
{
match = false;
break;
}
}
if(match)
return i;
}
}
return -1;
}
Ruby
def find_sub_str(str, sub_str)
match = false
for i in 0...str.length
if str[i] == sub_str[0]
for j in 1...sub_str.length
if str[i+j] == sub_str[j]
match = true
else
match = false
break
end
end
if match == true
return i
end
end
end
return -1
end