这段代码过去一直有效,直到我将 lambda 函数放入模块中。

这是 lambda 函数:

module GalleryGenerator
  @add_links_to_descriptions = lambda do |mutable_viewable_content|
    mutable_viewable_content.description = add_links_to_sources(mutable_viewable_content.description)
    return mutable_viewable_content
  end
  #...
end

以下是它的使用方式:
include GalleryGenerator

gallery = ViewableGallery.new(gallery_config.title, gallery_config.description, gallery_config.slug, \
gallery_config.sources, gallery_config.upload_date, gallery_config.map_url, gallery_config.map_title, \
gallery_config.year, viewable_photos).
update_using( \
    add_tabs_before_every_description_line(2), \
    @add_links_to_descriptions)

那是错误:
/home/mike/Development/Projects/FT/gallery_generator/lib/gallery_generator/viewable_gallery.rb:26:in `block in update_using': undefined method `call' for nil:NilClass (NoMethodError)
from /home/mike/Development/Projects/FT/gallery_generator/lib/gallery_generator/viewable_gallery.rb:25:in `each'
from /home/mike/Development/Projects/FT/gallery_generator/lib/gallery_generator/viewable_gallery.rb:25:in `update_using'
from bin/gallery_generator:32:in `<main>'

如果 lambda 消息不在模块中,则一切正常。我怀疑它现在在模块中的错误位置寻找@add_links_to_descriptions...

我怎样才能解决这个问题?谢谢!

最佳答案

试试这个:

module GalleryGenerator
  def self.add_links_to_descriptions
    lambda do |mutable_viewable_content|
      mutable_viewable_content.description = add_links_to_sources(mutable_viewable_content.description)
      return mutable_viewable_content
    end
  end
  #...
end

并用 GalleryGenerator.add_links_to_descriptions 调用它

关于ruby - 在 Ruby 中,如何引用模块中定义的 lambda?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27860515/

10-10 04:53