1

How to check if array includes string element?

address = 'London is a capital of GB'

  def get_location(address)
    all_cities = ['Amsterdam','Moscow','Krakow','London']
    city = all_cities.index {|x| x.match /address/ }
    if city
      return all_cities[city]
    else
      address
    end
  end

but its returns me full address

I needs to return the city's name from string

xxx
  • 506
  • 7
  • 16

4 Answers4

0

Use include? to check whether a string contains a substring.

address = 'London is a capital of GB'

def get_location(address)
  all_cities = ['Amsterdam','Moscow','Krakow','London']
  city = all_cities.index { |x| address.include? x }
  if city
    return all_cities[city]
  else
    address
  end
end

puts get_location address
# output: London
Community
  • 1
  • 1
Matthias
  • 7,432
  • 6
  • 55
  • 88
0

The issue with your code is .match is a method for regular expressions and none of your strings include address in their copy. So you should be getting your address every time because your if statement always goes to else.

'city = all_cities.index {|x| x.match /address/ } if city return all_cities[city]'

Try using .includes? as your method in this scenario.

0

I suggest using a regex with word breaks (\b)

cities = ['Amsterdam','Moscow','Krakow','London']

def find_city(cities, address)
  cities.find { |city| address =~ /\b#{city}\b/ }
end

find_city(cities, 'London is a capital of GB')
  #=> "London"
find_city(cities, 'Londonderry is not in London')
  #=> "London"
find_city(cities, 'Toledo is not the capital of BG')
  #=> nil
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Problem:

city = all_cities.index {|x| x.match /address/ }

It's treating address as a string rather than a variable and therefore every time your code enters else block and hence giving you the entire address.

Solution:

If you want a case insensitive comparison of strings use:

city = all_cities.index {|x| x.match /#{address}/i }

  • In the above statement observe that address has been wrapped inside #{}.
  • Passing the i option to match makes it case insensitive.

else use:

city = all_cities.index {|x| x.include? address }

because include? performs better than match

Sahil
  • 504
  • 6
  • 9