如何使用哈希表多个键生成一个组合值的字符串(Ruby)

3

我有一个下面这样的哈希表:

   a_hash = {
    "1" => "one",
    "2" => "two",
    "3" => "three",
    "4" => "four",
    "5" => "five",
    "6" => "six",
    "7" => "seven",
    "8" => "eight",
    "9" => "nine",
    "10" => "ten",
    "11" => "eleven",
    "12" => "twelve",
    "13" => "thirteen",
    "14" => "fourteen",
    "15" => "fifteen",
    "16" => "sixteen",
    "17" => "seventeen",
    "18" => "eighteen",
    "19" => "nineteen",
    "20" => "twenty",
    "30" => "thirty",
    "40" => "forty",
    "50" => "fifty",
    "60" => "sixty",
    "70" => "seventy",
    "80" => "eighty",
    "90" => "ninety",
    "00" => "hundred", #not sure this is right 
    "000" => "thousand"  #not sure this is right 

    } 

假设我的字符串输入是"99100"。 假设我想要的字符串输出是"九万九千一百"。 如果不想一个一个地键入每个键/值,该如何使用上述哈希表?我在考虑将我的字符串拆分成一个数组中的每个字符....然后对于该数组中的每个数字返回我的值?还有其他策略应该考虑吗?这是我目前的进展:
  puts "test the hash! Type a number hit enter"
  test_variable = gets.to_s.chomp
  puts a_hash[test_variable]

请发一些代码让我测试。谢谢!

2个回答

7

如果你只想要一个解决方案而不是使用哈希算法,那么Ruby Linguistics可能会对你有所帮助。

require 'linguistics'
include Linguistics::EN
numwords(99100)

=> "九万九千一百"

7
简短回答:不要自己做,找一个帮你实现。
然而,这可能是一个很酷的练习,也是一个有趣的问题。因此,忽略不重复造轮子的最佳实践...您可能需要区别对待数百和数千,因为您可以说“两百”,但“两七十”并没有太多意义。
这是我测试不足、未经优化的尝试。它是一个概念验证,我相信我已经忽略了很多情况。如果你想要更多的帮助,试着阅读其他人的源代码
首先,我们定义两个哈希表,一个用于数字,一个用于数量级(它们是不同的,因为它们可以在前面加上数字以便于相乘)。
class Integer
  NUMBERS = {
    1 => "one",
    2 => "two",
    3 => "three",
    4 => "four",
    5 => "five",
    6 => "six",
    7 => "seven",
    8 => "eight",
    9 => "nine",
    10 => "ten",
    11 => "eleven",
    12 => "twelve",
    13 => "thirteen",
    14 => "fourteen",
    15 => "fifteen",
    16 => "sixteen",
    17 => "seventeen",
    18 => "eighteen",
    19 => "nineteen",
    20 => "twenty",
    30 => "thirty",
    40 => "forty",
    50 => "fifty",
    60 => "sixty",
    70 => "seventy",
    80 => "eighty",
    90 => "ninety"
  }

  MAGNITUDES = {
    100 => "hundred",
    1000 => "thousand",
    1000_000 => "million"
  }
end

接下来,定义转换方法。

class Integer
  def to_text
    return nil if self == 0
    if NUMBERS.keys.include? self
      NUMBERS[self]
    elsif self < MAGNITUDES.keys.first
      base = maximum_fitting(NUMBERS, self)
      [NUMBERS[base], (self - base).to_text].compact * "-"
    else
      base = maximum_fitting(MAGNITUDES, self)
      quo, mod = self.divmod(base)
      [quo.to_text, MAGNITUDES[base], mod.to_text].compact * " "
    end
  end

  private

  def maximum_fitting(list, number)
    list.keys.select { |n| n <= number }.last
  end
end

使用它:

puts 2351.to_text
#=> "two thousand three hundred fifty-one"

puts 14330132.to_text
#=> "fourteen million three hundred thirty thousand one hundred thirty-two"

puts 1000000.to_text
#=> "one million"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接