Ruby方法调用而不定义变量

时间:2014-12-16 20:10:25

标签: ruby symbols

我对以下内容感到困惑: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

1 个答案:

答案 0 :(得分:2)

对于初学者来说,如果你是Ruby的初学者,那就不用费心去理解它了。这不是通常用Ruby做事的方式。

但是这里有一些解释:

:findSymbol,可能是:搜索或此示例中的其他内容。

您实际上可以使用其他变量来存储方法,而不是存储在城市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的方法(非常meta?)。

在上面的示例中,我们可以使用一个表示方法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
相关问题