根据哈希值转换字符串

时间:2016-02-13 03:41:11

标签: ruby hash

我正在尝试编写一个接受字符串和哈希的方法,并且"编码"基于散列键和值的字符串。

def encode(str,encoding)
end

str = "12#3"
encoding = {"1" => "one", "2"=> "two", "3"=> "three"}

我希望输出为"one two three"字符串中不是哈希键的任何字符都会替换为空字符串。

现在我的代码如下所示:

def encode(str, encoding)
  output = ""
  str.each_char do |ch|
    if encoding.has_key?(ch)
      output += encoding[ch]
    else
      output += ""
    end  
  end
  return output
end

感谢任何帮助

5 个答案:

答案 0 :(得分:2)

您可以使用String#gsub使用散列替换的形式,以及一个简单的正则表达式:

str = "12#3"
encoding = {"1"=>"one", "2"=>"two", "3"=>"three"}

首先创建一个新哈希,为encoding中的每个值添加一个空格:

adj_encoding = encoding.each_with_object({}) { |(k,v),h| h[k] = "#{v} " }
  #=> {"1"=>"one ", "2"=>"two ", "3"=>"three "}

现在执行替换并删除额外空格,如果encoding的其中一个键是str的最后一个字符:

str.gsub(/./, adj_encoding).rstrip
  #=> "one two three"

另一个例子:

"1ab 2xx4cat".gsub(/./, adj_encoding).rstrip
  #=> "one two"

Ruby确定str/./部分)的每个字符是否等于adj_encodeing的键。如果是这样,她将该键的值替换为该字符;否则她用空字符串('')替换该字符。

答案 1 :(得分:1)

您可以通过Regexp.union构建与您的密钥匹配的正则表达式:

re = Regexp.union(encoding.keys)
#=> /1|2|3/

scan使用该正则表达式出现键的字符串:

keys = str.scan(re)
#=> ["1", "2", "3"]

使用values_at获取相应的值:

values = encoding.values_at(*keys)
#=> ["one", "two", "three"]

join具有单个空格的数组:

values.join(' ')
#=> "one two three"

作为“一线”:

encoding.values_at(*str.scan(Regexp.union(encoding.keys))).join(' ')
#=> "one two three"

答案 2 :(得分:0)

尝试:

def encode(str, encoding)
  output = ""
  str.each_char do |ch|
    if encoding.has_key?(ch)
      output += encoding[ch] + " "
    else
      output += ""
    end  
  end
  return output.split.join(' ')
end

str = "12#3"
encoding = {"1" => "one", "2"=> "two", "3"=> "three"}

p encode(str, encoding) #=> "one two three"

答案 3 :(得分:0)

如果你期待"一两三"你只需要在concat行中添加一个空格,在返回之前,添加.lstrip以删除第一个空格。

提示:你不需要"否则"连接一个空字符串。如果"#"不匹配编码哈希,它将被忽略。

像这样:

#str = "12#3"
#encoding = {"1" => "one", "2"=> "two", "3"=> "three"}

def encode(str, encoding)
  output = ""
  str.each_char do |ch|
    if encoding.has_key?(ch)
      output += " " + encoding[ch]
    end  
  end
  return output.lstrip
end

# Output: "one two three"

答案 4 :(得分:0)

我愿意:

encoding = {"1" => "one", "2"=> "two", "3"=> "three"}
str = "12#3"
str.chars.map{|x|encoding.fetch(x,nil)}.compact.join(' ')

或者像这样的两行:

in_encoding_hash = -> x { encoding.has_key? x }
str.chars.grep(in_encoding_hash){|x|encoding[x]}.join(' ')