如何设置IF语句与数组内的值进行比较? (红宝石)

时间:2016-07-30 18:39:39

标签: ruby-on-rails ruby

是否可以设置条件语句(IF语句)将变量与迭代数组内部值的变量进行比较?我正在寻找类似的东西:

array_of_small_words = ["and","or","be","the","of","to","in"]
if word == array_of_small_words.each 
   # do thing
else
   # do another thing
end

基本上,我想把每个单词弄清楚,但不想为#34;小单词"做这些。我知道我可以做相反的事情并首先迭代数组,然后将每个迭代与单词进行比较,但我希望有更有效的方法。

sentence = ["this","is","a","sample","of","a","title"]
array_of_small_words = ["and","or","be","the","of","to","in"]
sentence.each do |word|
    array_of_small_words.each do |small_words|
       if word == small_words
          # don't capitalize word
       else
          # capitalize word
       end
    end
end

我不确定这是否可行,或者是否有更好的方法可以做到这一点?

谢谢!

3 个答案:

答案 0 :(得分:1)

sentence = ["this","is","a","sample","of","a","title"]
array_of_small_words = ["and","or","be","the","of","to","in"]

sentence.map do |word|
  array_of_small_words.include?(word) ? word : word.upcase
end
#⇒ ["THIS", "IS", "A", "SAMPLE", "of", "A", "TITLE"]

答案 1 :(得分:0)

您要找的是if array_of_small_words.include?(word)

答案 2 :(得分:0)

如果打包在方法和使用频率中,这应该比@ mudasobwa重复使用include?更快。然而,如果我在评论中提到的话,如果mudsie使用了一组查找(一个小的改变,他很清楚),那么不会更快。如果效率很重要,我会更喜欢使用set mod的mudsie方式来回答我的问题。在某种程度上,我只是在下面玩。

我认为他的小词是 和,或者,是,in,in,in,in 尽管

SMALL_WORDS = %w| and or be the of to in notwithstanding |
  #=> ["and", "or", "be", "the", "of", "to", "in", "notwithstanding"] 
(SMALL_WORDS_HASH = SMALL_WORDS.map { |w| [w.upcase, w] }.to_h).
  default_proc = proc { |h,k| h[k]=k }

测试:

SMALL_WORDS_HASH
  #=> {"AND"=>"and", "OR"=>"or", "BE"=>"be", "THE"=>"the", "OF"=>"of",
  #    "TO"=>"to", "IN"=>"in", "NOTWITHSTANDING"=>"notwithstanding"} 
SMALL_WORDS_HASH["TO"]
  #=> "of" 
SMALL_WORDS_HASH["HIPPO"]
  #=> "HIPPO" 

def convert(arr)
  arr.join(' ').upcase.gsub(/\w+/, SMALL_WORDS_HASH)
end

convert ["this","is","a","sample","of","a","title"]
  #=> "THIS IS A SAMPLE of A TITLE"