this is a begginer question about including .rb files.
I would like to have access to an array declared in another rb file. My main program goes like this :
#!/usr/bin/env ruby
load 'price.rb'
[...]
max_price = price[az][type] * 2
[...]
and here is the price.rb :
price = {'us-east-1' => {'t1.micro' => 0.02, 'm1.small' => 0.08, 'c1.medium' => 0.165, 'm1.large' => 0.320 },
'us-west-1' => {'t1.micro' => 0.02, 'm1.small' => 0.08, 'c1.medium' => 0.165, 'm1.large' => 0.320 },
'eu-west-1' => {'t1.micro' => 0.02, 'm1.small' => 0.085, 'c1.medium' => 0.186, 'm1.large' => 0.340 }
}
When I run the main script I get this error :
Error: undefined local variable or method `price' for main:Object
What do you think ?
The best way to export data from one file and make use of it in another is either a class or a module.
An example is:
In another file you can
requirethis. Usingloadis incorrect.You can even shorten this by using
include:What you’ve done is a bit difficult to use, though. A proper object-oriented design would encapsulate this data within some kind of class and then provide an interface to that. Exposing your data directly is counter to those principles.
For instance, you’d want a method
InstancePrices.price_for('t1.micro', 'us-east-1')that would return the proper pricing. By separating the internal structure used to store the data from the interface you avoid creating huge dependencies within your application.