Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将英语句子转换成ruby键值对的最佳方法是什么?_Ruby - Fatal编程技术网

将英语句子转换成ruby键值对的最佳方法是什么?

将英语句子转换成ruby键值对的最佳方法是什么?,ruby,Ruby,我想在键值对中转换以下句子,比如({total\u amount:discount\u amount}) 我该怎么办?如果我能从……开始得到任何提示,那将很有帮助。我假设每个感兴趣的句子都是这样的: $XX....for....$YY $XX....off....$YY 或者像这样: $XX....for....$YY $XX....off....$YY 其中,XX和YY是非负整数,“for”和“off”是告诉您如何处理这两个数字的关键字。如果是这样,您似乎希望: arr = ["$10

我想在键值对中转换以下句子,比如({total\u amount:discount\u amount})


我该怎么办?如果我能从……开始得到任何提示,那将很有帮助。

我假设每个感兴趣的句子都是这样的:

$XX....for....$YY
$XX....off....$YY
或者像这样:

$XX....for....$YY
$XX....off....$YY
其中,
XX
YY
是非负整数,
“for”
“off”
是告诉您如何处理这两个数字的关键字。如果是这样,您似乎希望:

arr = ["$10 off $30 of food", "$30 of awesome for $10", "$20 Sneakers for $5"]
让我们首先在扩展模式下定义一个正则表达式:

r = /
    \$        # match dollar sign
    (\d+)     # match one or more digits in capture group 1
    .*?       # match any number of any character lazily
    \b        # word boundary (so "buzzoff" is not matched)
    (for|off) # match "for" or "off" in capture group 2
    \b        # another word boundary
    .*?       # match any number of any character lazily  
    \$        # match dollar sign
    (\d+)     # match one or more digits in capture group 3
    /x        # extended mode for regex def

arr.each_with_object([]) do |s,a|
  s[r]
  f,l = $1.to_i, $3.to_i
  case $2
  when "for" then a << [f,f-l]
  when "off" then a << [l,f]
  end
end
  #=> [[30, 10], [30, 20], [20, 15]] 
我们现在执行块计算:

s[r] #=> "10 off $30"
三个捕获组的值为:

$1 #=> "10" 
$2 #=> "off" 
$3 #=> "30" 
因此:

  f,l = $1.to_i, $3.to_i
    #=> [10, 30]
因此:

案例$2

如果是“for”,则可以使用该方法将数字提取到数组中,然后将数组的元素转换为哈希。符号不能以数字开头。downvote和vote to close是因为您的问题不清楚。您需要编辑以解释为什么“$30食品的$10折扣”应该返回
{30=>10}
,而“$5的$20运动鞋”应该返回
{20=>15}
。这是否取决于“off”或“for”两个词出现在美元金额之间(正如我在回答中所假设的那样)?您也可以将
{a:1}
写为
{a:a=>1}
,但
:10
不是有效的符号,因此必须编写
{10=>1}
  f,l = $1.to_i, $3.to_i
    #=> [10, 30]
  case $2
    when "for" then a << [f,f-l]
    when "off" then a << [l,f]
  end
  case "off"
    when "for" then [] << [10, 10-30]
    when "off" then [] << [30, 10]
  end
    #=> [[30, 10]] 

  a #=> [[30, 10]] 
def read_discount(file_name)
    File.foreach(file_name) do |line|
        /[^\d]*(\d+)[^\d]*(\d+)/ =~ line
        puts "#{$1}:#{$2}" if $1
    end
end

read_discount("31621358.txt")