goatstash
goatstash

Reputation: 162

count the distance between to strings in an array Ruby

i have an array

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

how could I count the distance between the two strings? expected output 5.

Upvotes: 0

Views: 103

Answers (2)

Rajagopalan
Rajagopalan

Reputation: 6064

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

Code

p (line_one.index("flinders street")...line_one.index("glenferrie")).count

output

5

Upvotes: 0

user16452228
user16452228

Reputation:

The first thing that comes to mind:

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

(line_one.find_index(user_input1) - line_one.find_index(user_input2)).abs
#=>  5

Upvotes: 4

Related Questions