总结字符串重合乘以散列值

时间:2017-02-01 01:58:26

标签: ruby regex

我需要总结一个字符串中一个(数字)字符的重合次数,该字符串在一个哈希值中与其值匹配,只有当它严格地出现而没有任何其他字符时,就是说没有前缀或后缀

s = "three twot 1three one three"
method(s) #=> 6
method("one on one") #=> 2
method("five monkeys in three farms") #=> 8
method("") #=> 0
method("fivethreeone") #=> 0

我可以总结一个特定值,但无法使用多个值:

    s = "three twot 1$three one three"

    def method(string)
        num = {one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }

    num.each {|k,v|  sum += string.scan(/\b{num.key(v)}\b/).count*num[num.key(v)]}  

    end

    p secret_code(s)
    p secret_code("one on one")
    p secret_code("five monkeys in three farms")
    p secret_code("")
    p secret_code("fivethreeone")

2 个答案:

答案 0 :(得分:1)

这是使用Array#reduce的潜在解决方案:

WORDS_AND_DIGITS = {one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }

s = "three twot 1$three one three"

def method(string)
  string.split.reduce(0) do |sum, number|
    sum += WORDS_AND_DIGITS[number.to_sym].to_i
    sum
  end
end

你绝对可以搞砸重构来取出#to_sym#to_i,但这可以实现你所描述的功能。如果哈希中不存在该键,则返回nil,因此它被强制转换为整数0

答案 1 :(得分:0)

试试这个:

Encrypter()

供参考:

str = "three twot 1three one three"
number_map = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }
str.split.map { |word| number_map[word.to_sym] }.compact.inject(:+)    # 7