I have a YAML file that contains a bunch of ranges as the values:
<main>': undefined method to_a'
data = YAML.load_file('./lib/lists/yamls/combat_power.yml')
print 'Enter a name: '
name = gets.chomp.capitalize
new_data = data['combat_power'][name]
Enter a name: Charmeleon
go.rb:10:in `<main>': undefined method `to_a' for "(18.5..1557)":String (NoMetho
Did you mean? to_yaml
A few things:
Ruby's YAML implementation doesn't unserialize ruby objects without you explicitly telling it to do so. This is both a security feature (some code is dangerous to unserialize), as well as a somewhat impossible task to accomplish (how is it supposed to know what you intend to be evaluated?). So, to turn the range string into an actual Ruby
Range object, you need to
require 'yaml' data = YAML.load_file('./yamls.yaml') print 'Enter a name: ' name = gets.chomp.capitalize new_data = data['combat_power'][name] puts eval(new_data).class # => Range puts eval(new_data).to_a
Note that you should only
eval text that you explicitly wrote--
evaling code from a random source, such as user input, can be a serious security issue. But as long as you are only
evaling values from that YAML file that you wrote, you should be fine.
Ruby doesn't know how to enumerate a range of floats, so your
(17.2..1454).to_a will throw a
TypeError. This is because the interpreter can't possibly know if you want to increment by
+0.1, etc. I'm not sure how you want to solve this issue, since the solution will be based on the meaning of your data specifically.