Home > Net >  count the distance between to strings in an array Ruby
count the distance between to strings in an array Ruby

Time:02-13

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.

CodePudding user response:

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

CodePudding user response:

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

Code

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

output

5
  • Related