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

1
  • Could you explain what do you want exactly (the input and the output)?
    – Walid Da.
    Commented Mar 20, 2015 at 20:48

4 Answers 4

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
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
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.