简体   繁体   English

访问Ruby块中的函数

[英]Accessing functions inside a Ruby block

I'm working inside a one-off Ruby script (so not inside an explicitly defined module or class) and I'm having a hard time accessing a function I've defined earlier in the script, from within a .each block. 我正在使用一次性的Ruby脚本(因此不在显式定义的模块或类中),并且很难从.each块中访问我在脚本中先前定义的函数。

def is_post?(hash)
  if hash["data"]["post"] == "true" #yes, actually a string
    true
  else 
    false
  end
end

#further down

threads["data"]["children"].each do |item|
  puts item["data"]["title"] unless item.is_post?
end

Result: 结果:

in 'block in <top (required)>': private method `is_post?' called for #<Hash:0x007f9388008cf0\> (NoMethodError)

threads is a very, very nested hash. threads是一个非常非常嵌套的哈希。 A hash, contaning a hash of arrays, the arrays contain a hash with header data, which contains another hash with the rest of the details. 一个散列,包含数组的散列,这些数组包含一个包含标头数据的散列,该散列包含另一个包含其余详细信息的散列。 A bit messy, but I didn't write the module that generates that :P 有点混乱,但我没有编写生成该:P的模块

The idea is to iterate through the arrays and retrieve the data from each one. 这个想法是遍历数组并从每个数组中检索数据。

My questions are: 我的问题是:

  • What manner of shenaniganery do I need to do to access my is_post? 访问is_post?我需要做什么方式is_post? function from within the block? 从块内部功能?

  • Why is it coming up as a private method when I don't have any private declarations anywhere in my script? 当我的脚本中没有任何私有声明时,为什么将它作为私有方法出现?

Kernel vs instance method, self vs argument Kernel与实例方法, self与参数

def is_post?(hash)
  ...
end

By defining the methods in that way, you are defining a method for Kernel . 通过以这种方式定义方法,就可以为Kernel定义方法。 You have the choice of either calling this method through Kernel.is_post?(hash) , or is_post?(arg) . 您可以选择通过Kernel.is_post?(hash)is_post?(arg)调用此方法。 Unless item is the Kernel object, you wont have defined the method is_post? 除非itemKernel对象,否则您将不会定义is_post?方法is_post? for it. 为了它。

Your method takes exactly one argument. 您的方法只接受一个参数。 In case item has a is_post? 如果项目有一个is_post? method, by doing item.is_post? 方法,通过执行item.is_post? , you are not providing an argument but only self to the method. ,您不提供参数,而仅提供方法的self

The solution 解决方案

You probably should replace 您可能应该更换

item.is_post?

by 通过

is_post?(item)

You don't want to call is_post? 您不想致电is_post? on the item (it's a Hash like the error message says). item (它是一个Hash如错误消息中所述)。 What you want is the following: 您想要的是以下内容:

threads["data"]["children"].each do |item|
  puts item["data"]["title"] unless is_post?(item)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM