如何检查数组是否包含字符串元素?
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
但它会返回我的完整地址
我需要从字符串
返回城市的名字答案 0 :(得分:0)
使用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
答案 1 :(得分:0)
您的代码存在的问题是.match是一种正则表达式的方法,并且您的所有字符串都不包含其副本中的地址。所以你应该每次都得到你的地址,因为你的if语句总是转到其他地方。
'city = all_cities.index {|x| x.match /address/ }
if city
return all_cities[city]'
尝试使用.includes?作为此方案中的方法。
答案 2 :(得分:0)
我建议使用带分词符(\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
答案 3 :(得分:0)
<强>问题:强>
city = all_cities.index {|x| x.match /address/ }
它将address
视为字符串而不是变量,因此每当您的代码进入else块时,就会为您提供整个地址。
<强>解决方案:强>
如果您想要对字符串进行不区分大小写的比较,请使用:
city = all_cities.index {|x| x.match /#{address}/i }
address
已被#{}
包裹。 i
选项传递给匹配项会使其不区分大小写。否则使用:
city = all_cities.index {|x| x.include? address }
因为include?
的效果优于match