我想过滤收到的信息:
news = [
'One day bla-bla-bla',
'Long time ago bla-bla',
]
并传递包含我指定的单词之一的消息:
mywords = ['ago', 'time', 'hero']
我试过了:
messages = []
news.each do |item|
mywords.each do |word|
if item.include?(word)
messages << item
return
end
end
end
Rails或Ruby的方法是什么?
答案 0 :(得分:1)
mywords = %w(ago time hero)
news = [
'One day bla-bla-bla',
'Long time ago bla-bla'
]
news.select { |n| mywords.any? { |w| n =~ /\b#{w}\b/ } }
#⇒ ["Long time ago bla-bla"]
甚至更好:
news.select { |n| n =~ Regexp.union(mywords) }
#⇒ ["Long time ago bla-bla"]
请注意,我的答案比其他两个[目前发布的]更强大,因为它不会与“超人回电”的消息相提并论“男人”这个词。
答案 1 :(得分:1)
这样可以解决问题:
news.select { |item| mywords.any? { |word| item.include? word } }
答案 2 :(得分:0)
在一行
news.select { |item| my_words.any? { |word| item.include? word } }
答案 3 :(得分:0)
include不检查单词而是检查字符串。而是检查新闻是否包含整个单词,而不是其中的一部分:
var nodeDataArray = [
{isGroup:true,key:-1,text:"Service Parameters",xy:"210 31.999999999999996"},
{ isGroup: true, key: -2, text: "Device Model", xy: "435 36.000000000000014"}
];
var linkDataArray = [];
var i=0;
function loop(from) {
return function (a) {
var f = i;
if(a.yang_type!='' && a.name!=''){
nodeDataArray.push({ key:i,Data: a.yang_type + " " + a.name, group: -1 });
//c=c+a.name;
//console.log("c:",c);
//console.log("Data:",a.yang_type);
//linkDataArray.push({ from: i, to: i+1 });
}
if(a.name!='' && a.value!=''){
nodeDataArray.push({ key:i,Data: a.name + " " + a.value, group: -1 });
//c=c+a.name+a.value;
console.log("c:",c);
//linkDataArray.push({ from: 0, to: i+1 });
}
if (from !== undefined) {
linkDataArray.push({ from: from, to: i });
}
i++;
if (Array.isArray(a.children)) {
a.children.forEach(loop(f));
}
//console.log("c:",c);
};
}