0

Hi i just started learning ruby and i'm trying to loop through an array i created looking like this:

server[0] = ['hostname' => 'unknown01', 'ip' => '192.168.0.2', 'port' => '22']
server[1] = ['hostname' => 'unknown02', 'ip' => '192.168.0.3', 'port' => '23']
server[2] = ['hostname' => 'unknown03', 'ip' => '192.168.0.4', 'port' => '24']

i tried using this code:

i=0
server[i].each do |x|
    print x['hostname']
    print x['ip']
    i+=1
end

but it only loops through server[0] how i can loop through server[0-3]

0

3 Answers 3

5

You don't need to use i at all, just do this:

server.each do |x|
    print x['hostname']
    print x['ip']
end
Sign up to request clarification or add additional context in comments.

Comments

1

What you're doing is setting i to 0, so when you get to the server[i].each, you're calling server[0].each. Even though you increment i that doesn't change what you're enumerating over. The correct code is:

server.each

to enumerate over every element in server.

Comments

0

This probably isn't doing what you think it is. Since you're putting your key/value pairs inside of square brackets, it winds up being an array of one hash (other languages call them maps and dictionaries). Probably you want to exchange your square brackets with curly brackets like this:

servers = []
servers[0] = {'hostname' => 'unknown01', 'ip' => '192.168.0.2', 'port' => '22'}
servers[1] = {'hostname' => 'unknown02', 'ip' => '192.168.0.3', 'port' => '23'}
servers[2] = {'hostname' => 'unknown03', 'ip' => '192.168.0.4', 'port' => '24'}

But since you're just setting each one by its index, you don't need to build it up this way, you can just place them in their respective positions within the array.

servers = [
  {'hostname' => 'unknown01', 'ip' => '192.168.0.2', 'port' => '22'},
  {'hostname' => 'unknown02', 'ip' => '192.168.0.3', 'port' => '23'},
  {'hostname' => 'unknown03', 'ip' => '192.168.0.4', 'port' => '24'},
]

Then to iterate over each one you can do:

servers.each do |server|
  puts server['hostname']
  puts server['ip']
  puts
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.