方法ruby中散列的未定义局部变量

出于某种原因,我得到了

NameError: undefined local variable or method `states' for main:Object 

虽然国家是明确定义的。 这里发生了什么?

在irb中我添加了状态并使用状态[:CA]访问它,但是当我把它放在一个方法中时我得到了那个错误。

 states = { CA: 'California', FL: 'Florida', MI: 'Michigan', NY: 'New York', OR: 'Oregon', } states[:CO] = 'Colorado' states[:HI] = 'Hawaii' cities = { CA: ['Alameda', 'Apple Valley', 'Exeter'], FL: ['Exeter', 'Amelia Island', 'Bunnell'], MI: ['Ann Arbor', 'East China', 'Elberta'], NY: ['Angelica', 'Apalachin', 'Canadice'], OR: ['Amity', 'Boring', 'Camas Valley'], CO: ['Blanca', 'Crestone', 'Dillon', 'Fairplay'], HI: ['Kailua', 'Hoopili', 'Honolulu'], } def describe_state state puts state description = "#{state.to_s} is for #{states[state]}." description << " It has #{citites[state].length} major cities:" cities[state].each do |x| ' ' << description end end puts describe_state :CA 

states是一个局部变量(因为它以小写字母开头)。 局部变量是它们定义的范围的本地变量(这就是为什么它们被称为局部变量,毕竟)。 因此, states在脚本的范围内定义,但不在describe_state方法的范围内。

方法范围不嵌套,唯一嵌套的范围是块范围,因此您需要使用块。 值得庆幸的是,有一个名为define_method的方法,它从块创建一个方法:

 states = { CA: 'California', FL: 'Florida', MI: 'Michigan', NY: 'New York', OR: 'Oregon', } states[:CO] = 'Colorado' states[:HI] = 'Hawaii' cities = { CA: ['Alameda', 'Apple Valley', 'Exeter'], FL: ['Exeter', 'Amelia Island', 'Bunnell'], MI: ['Ann Arbor', 'East China', 'Elberta'], NY: ['Angelica', 'Apalachin', 'Canadice'], OR: ['Amity', 'Boring', 'Camas Valley'], CO: ['Blanca', 'Crestone', 'Dillon', 'Fairplay'], HI: ['Kailua', 'Hoopili', 'Honolulu'], } define_method(:describe_state) do |state| "#{state} is for #{states[state]}. " \ "It has #{cities[state].length} major cities: #{cities[state].join(', ')}" end puts describe_state :CA #=> CA is for California. It has 3 major cities: Alameda, Apple Valley, Exeter 

该方法无法访问外部变量。 您可以使用实例变量。 从文档 :

实例变量在同一对象的所有方法中共享。

例:

 @states = { CA: 'California', FL: 'Florida', MI: 'Michigan', NY: 'New York', OR: 'Oregon', } @states[:CO] = 'Colorado' @states[:HI] = 'Hawaii' @cities = { CA: ['Alameda', 'Apple Valley', 'Exeter'], FL: ['Exeter', 'Amelia Island', 'Bunnell'], MI: ['Ann Arbor', 'East China', 'Elberta'], NY: ['Angelica', 'Apalachin', 'Canadice'], OR: ['Amity', 'Boring', 'Camas Valley'], CO: ['Blanca', 'Crestone', 'Dillon', 'Fairplay'], HI: ['Kailua', 'Hoopili', 'Honolulu'], } def describe_state state description = "#{state.to_s} is for #{@states[state]}." description << " It has #{@cities[state].length} major cities: " description << @cities[state].join(', ') end puts describe_state :CA #=> CA is for California. It has 3 major cities: Alameda, Apple Valley, Exeter 

(我在describe_state修复了一个小错误)

状态和城市没有定义在函数中传递它们之类的

 def describe_state state, states, cities .. end puts describe_state :CA, states, cities 

将工作