记忆在过程中有效吗?

does memoization works inside of a proc?

我有以下方法:

def download_link_for(site,title=nil)
  template = proc {|word|(title ?  "%s_#{title}_csv": "%s_csv") % word}

  if site.send(template.call("update")) == false
    x.a "Generate", :href => "/#{template.call("generate")}/#{site.id}"
  else
    xpr "Generating.."
  end
  if site.send(template.call("latest")) > 0 && site.send(template.call("update")) == false
    %|

  <a href="/#{template.call("download")}/#{site.id}" class="tooltip-left" title="Download the #{title} as a .csv file" id="download_pdf">
    <img src="/images/csv_download.png" alt="Download"/>
  </a>
  (#{timedate(site.send(template.call("latest")))})
    |

  end
end

问题出在程序上。 我想知道 memoization 是否在 proc 中起作用?专门针对:

title ?  "%s_#{title}_csv": "%s_csv"

请记住,我正在使用 ruby 1.8.7,但也欢迎提供有关 1.9+ 的信息。

主要问题是 proc 内部的三进制只需要在第一次计算,所以我不希望它在每次调用 proc get 时都计算它。

编辑:我的想法是像这样使用柯里化:

template = proc {|tem,word|tem % word}.curry(type ?  "%s_#{type}_csv" : "%s_csv")

但出于某种原因,它一直在响应 no implicit conversion of String into Integer 我认为 ruby 将 % 解释为模数而不是字符串模板。 即使像 "#{tem}" 这样包装 tem 也没有真正起作用。

此外,curry 对我来说并不适用,因为它在 1.8.7 中不可用,但值得一试。

不确定为什么需要咖喱。不能直接用一个实例变量来store/memoize三元运算的结果吗?

template = proc { |word| @title ||= (title ? "%s_#{title}_csv" : "%s_csv"); @title % word }

在 irb 中:

template = proc { |word| @title ||= word }

template.call "hello"
 => "hello" 

template.call "goodbye"
 => "hello"