【问题标题】:Ruby method calls without defining variables没有定义变量的 Ruby 方法调用
【发布时间】:2014-12-16 20:10:25
【问题描述】:

我对 :find 来自第 17 行以及 :findcity... 的来源感到非常困惑...您是如何在 ruby​​ 的预定义方法调用中调用函数的???

 cities = {'CA' => 'San Francisco',
 'MI' => 'Detroit',
 'FL' => 'Jacksonville'}

 cities['NY'] = 'New York'
 cities['OR'] = 'Portland'

 def find_city(map, state)
   if map.include? state
     return map[state]
   else
     return "Not found."
   end
 end

 # ok pay attention!
 cities[:find] = method(:find_city)

 while true
   print "State? (ENTER to quit) "
   state = gets.chomp

   break if state.empty?

   # this line is the most important ever! study!
   puts cities[:find].call(cities, state)
 end

【问题讨论】:

  • 您正在使用:find 键插入代表find_cityMethod 对象。
  • 请不要在代码示例中复制行号。它使调试示例变得更加困难。
  • ...find_city 是在您调用method(:find_city) 的上面直接定义的方法。 :find_city 符号用于捕获方法本身。然后用cities[:find].call(cities, state) 调用它。
  • 如果正如代码 cmets 所暗示的那样,这是课程材料,那么可能是时候寻找另一位讲师了。很少 Ruby 爱好者会认为这是对语言特性的传统或有用的应用。
  • @mattt 这是来自Learn Ruby the Hard Way(早期版本)。

标签: ruby symbols


【解决方案1】:

对于初学者,如果您是 Ruby 的初学者,请不要费心去理解它。这不是 Ruby 中常用的处理方式。

但这里有一些解释:

:findSymbol,在此示例中可能是 :search 或其他内容。

您实际上可以使用不同的变量来存储方法,而不是存储在城市Hash 中。像这样:

# Instead of doing this
hash = {} # => {}
hash[:puts_method] = method(:puts)
hash[:puts_method].call("Foo")
# Foo

# You can just
puts_method = method(:puts)
puts_method.call("Foo")
# Foo

find_city 是您的代码中定义的方法。将符号 :find_city 传递给方法 method 会返回一个对象,该对象代表类 Method 的该方法(非常元,嗯?)。

所以就像上面的例子一样,我们可以有一个代表方法puts的对象,我们可以使用它发送方法call调用它。

the_puts = method(:puts) 
# => #<Method: Object(Kernel)#puts>
the_puts.call("Hey!")
# Hey!
# => nil

# Which is the same as simply doing
puts("Hey!")
# Hey!
# => nil

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 2011-02-01
    • 2011-07-24
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多