使用此代码格式:
class Country
CODE_TO_NAME = {
:us => 'United States',
:mx => 'Mexico',
:fr => 'France',
:gr => 'Germany'
}
def self.name(code)
# Write some code here
end
end
puts Country.name(ARGV.shift)
我希望我的代码以这样的输出运行:
$ ruby country_name.rb
Code not specified
$ ruby country_name.rb ca
Not match
$ ruby country_name.rb us
United States
$ ruby country_name.rb mx
Mexico
我应该怎么做?
答案 0 :(得分:1)
因此,我们需要关注三种情况:
在第一种情况下,ARGV.first
将是nil
。我们可以向nil
添加CODE_TO_NAME
键,并显示相应的消息。
在第二种情况下,索引到CODE_TO_NAME
将返回默认值,因此我们可以将默认值设置为适当的消息。
在第三种情况下,我们从命令行获取的代码将是String
,而不是Symbol
,因此,如果我们将CODE_TO_NAME
中的键更改为{{1} } s,我们可以直接索引到String
,而无需进行任何转换。
CODE_TO_NAME
答案 1 :(得分:0)
首先,将代码的路径命名为country_name.rb
。然后,将Country.name
定义为:
def self.name(code)
case
when code.nil? then "Code not specified"
when name = CODE_TO_NAME[code.to_sym] then name
else "Not match"
end
end
答案 2 :(得分:0)
其他选项,在调用方法之前检查代码:
class Country
# no changes here
def self.name(code)
return "Not found" unless CODE_TO_NAME.has_key? code
CODE_TO_NAME[code]
end
end
code = ARGV[0]
abort("Code not specified") unless code
puts Country.name(code.to_sym)