Array includes string ruby?

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


ANSWERS:


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

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.


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

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



 MORE:


 ? How do I check if a string contains a specific word?
 ? How do I check if a string contains a specific word?
 ? How do I check if a string contains a specific word?
 ? PHP - How to check if a string contain any text
 ? PHP - How to check if a string contain any text
 ? PHP - How to check if a string contain any text
 ? PHP - How to check if a string contain any text
 ? How do I check if a string contains a specific word?
 ? How can I check if a word is contained in another string using PHP?
 ? How to check on the if statement for the contain text on PHP dom?