Reputation: 134
I'm utilizing yaml to create a configuration file to automate creating machine setup files. I'm have some basic ruby scripting experience but looking to start utilizing classes more to make things cleaner and get better at programming.
My YAML names config.yaml:
`machine_configurations:
MACHINE_NAME_1:
Settings:
MACHINE_NAME_2:
Settings:`
I have a class machine_builder.rb
`require 'yaml'
class MachineBuilder
def initialize
@config = YAML.load_file("config.yaml")
end
def machine_list
@config['machine_configurations'].each do |k,v|
k
end
end
end
What I'm trying to figure out how to do is to store an array of the machine configuration strings
I've testing trying to use
test = MachineBuilder.new
machine_list = []
machine_list << test.machine_list
what I'm trying to get for a result is
machine_list = ['MACHINE_NAME_1','MACHINE_NAME_2']
but I keep getting the entire hash key and values stored in the array.
machine_list = ['MACHINE_NAME_1 => Settings: ...',' MACHINE_NAME_2 => Settings...']
I've tried changing the method using the following but I guess I'm missing something.
def machine_list
@config['machine_configurations'].each do |k,v|
return k
end
end
This attempt only returns one value, and I'm assuming that this is because return exits the loop once the one value is found.
def machine_list
@config['machine_configurations'].each do |k,v|
puts k
end
end
I guess in the end I'm also trying to figure out what is the best practice in to iterate and return values in a method or help to better understand using methods and returning values using the methods.
Upvotes: 0
Views: 105
Reputation: 1023
The each method returns the original enumerable object it was called upon, this is why you keep getting the entire hash when you call the machine_list method.
You can try the following code to get an array of the keys of the @config
hash:
def machine_list
@config['machine_configurations'].keys
end
and then:
test = MachineBuilder.new
machine_list = test.machine_list
this way the result will be:
machine_list = ['MACHINE_NAME_1','MACHINE_NAME_2']
Upvotes: 2