Reputation: 3
Is it possible to set a conditional statement (IF statement) comparing a variable against a variable that iterates through the values inside an array? I was looking for something like:
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
Basically, I want to capitalize each word but don't want to do it for "small words". I know I could do the the opposite and iterate through the array first and then compare each iteration with the word but I was hoping there would be a more efficient way.
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
I'm not really sure if this is possible or if there is a better way of doing this?
Thank you!
Upvotes: 0
Views: 189
Reputation: 110665
This should be faster than @mudasobwa's repeated use of include?
if packaged in a method and used frequency. It would not be faster, however, if mudsie used a set lookup (a minor change, of which he is well-aware), as I mentioned in a comment. If efficiency is important, I'd prefer mudsie's way with the set
mod over my answer. In a way I was just playing around below.
I've assumed he small words are and, or, be, the, of, to, in and notwithstanding.
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 }
Test:
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"
Upvotes: 0
Reputation: 121000
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"]
Upvotes: 1
Reputation: 1767
What you're looking for is if array_of_small_words.include?(word)
.
Upvotes: 0