在Ruby中,比较一个数组和散列函数,如果键与数组元素匹配,则返回/替换它与键的值

时间:2018-02-23 23:51:16

标签: arrays ruby loops hash compare

在run中我有一个名为dictionary的哈希函数。 我试图获取键:值对的散列并通过字符串/句子循环它们。 我将字符串转换为数组,然后我想用replacement_words哈希循环该数组。如果数组元素= =哈希中的键,那么我想用键的值替换它。

def dictionary
  replacement_words={
    'hello' => 'hola',
    'two' => 'dos',
    'goodbye' => 'adios',
    'ten' => 'diez',
    '4' => 'cuatro',
    'house' => 'casa',
    'cat' => 'gato'
  }
end 

下面我需要调用字典哈希函数,我想返回带有替换字的字符串。 '你好'应该用'Hola'代替。

def spanglish(sentence)
  array=[]
  main_key=dictionary.to_a
  main_value=dictionary.values
  sentence_array=tweets.split(" ")
  sentence_array.collect do |word|
     if word == "to"
       array << "2"
     else
       array << word
    end 
  end 
  array.join(" ")
  array


end

注意:仅使用ruby编程而不是ruby on rails。

示例输入:

"Hello it has been two days since your cat has visited my house"

输出:

"Hola it has been dos days since your gato has visited my casa"

3 个答案:

答案 0 :(得分:1)

您可以映射句子中的每个单词,并尝试访问每个单词的replacement_words哈希,如果您可以获取特定键的值,那么您就完成了,如果没有,那么您使用相同的单词:

replacement_words = {
  'hello' => 'hola',
  'two' => 'dos',
  'goodbye' => 'adios',
  'ten' => 'diez',
  '4' => 'cuatro',
  'house' => 'casa',
  'cat' => 'gato'
}

sentence = 'Hola it has been dos days since your gato has visited my casa'
p sentence.split.map { |word| replacement_words[word.downcase] || word }.join(' ')
# "hola it has been dos days since your gato has visited my casa"

由于Hello不在replacement_words中,因此它不会获取该值,但是您可以对该单词进行缩写,这将使该句子应用键,因为它在哈希值中。

答案 1 :(得分:1)

可能是简单的事情吗?

replacement_words = {
  'hello'   => 'hola',
  'two'     => 'dos',
  'goodbye' => 'adios',
  'ten'     => 'diez',
  '4'       => 'cuatro',
  'house'   => 'casa',
  'cat'     => 'gato',
  'lola'    => 'gertrude'
}

str = "Hello it has been two days since Lola has visited my house"

h = dictionary
str.gsub(/\b\p{Alpha}+\b/) do |word|
  downword = word.downcase
  if h.key?(downword)
    downword == word ? h[downword] : h[downword].capitalize
  else
    word
  end
end
  #=> "Hola it has been dos days since Gertrude has visited my casa"

答案 2 :(得分:0)

String#gsub接受哈希作为替代:

string.gsub(Regexp.union(replacement_words.keys), replacement_words)

为了使其工作,应该预先更新初始哈希以区分大写单词:

replacement_words =
  replacement_words.merge(
    replacement_words.
      reject { |e| e =~ /\A\d/ }.
      map { |h| h.map(&:capitalize) }.
      to_h
    )