Brando__
Brando__

Reputation: 365

Passing Ruby array elements to a method

I'm not a programmer, but I find myself writing some simple ruby and aren't sure about a few things.

I have the following function

def resolve_name(ns_name)
  ip = Resolv.getaddress(ns_name)
  return ip
end

and the array

array = ['ns-1.me.com', 'ns-2.me.com']

What I want to do is to pass every element in the array to the function to be evaluated, and spit out to... something. Probably a variable. Once I have the resolved IPs I'll be passing them to an erb template. Not quite sure yet how to handle when there may be 1 to 4 possible results either.

What I want think I need to do is do an each.do and typecast to string into my function, but I haven't been able to figure out how to actually do that or phrase my problem properly for google to tell me.

http://ruby-doc.org/core-2.0.0/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion Doesn't quite have what I'm looking for.

irb(main):010:0> resolved = resolve_name(array)
TypeError: no implicit conversion of Array into String

Any suggestions?

Upvotes: 1

Views: 2006

Answers (2)

Thilo
Thilo

Reputation: 17735

Take a look at the documentation for ruby's Enumerable, which arrays implement. What you're looking for is the map method, which takes each element of an enumerable (i.e. an array) and passes it to a block, returning a new array with the results of the blocks. Like this:

array.map{|element| resolve_name(element) }

As an aside, in your method, you do not need to use a local variable if all you're doing with it is returning its value; and the return statement is optional - ruby methods always return the result of the last executed statement. So your method could be shortened to this:

def resolve_name(ns_name)
  Resolv.getaddress(ns_name)
end

and then you really all it's doing is wrapping a method call in another. So ultimately, you can just do this (with array renamed to ns_names to make it self-explanatory):

ns_names = ['ns-1.me.com', 'ns-2.me.com']
ip_addresses = ns_names.map{|name| Resolv.getaddress(name) }

Now ip_addresses is an array of IP addresses that you can use in your template.

Upvotes: 5

s1mpl3
s1mpl3

Reputation: 1464

If you pass an array you could do:

def resolve_name(ns_name)
  res = []
  ns_name.each do |n|
    res << {name: n, ip:  Resolv.getaddress(name) } 
  end   
  res
end

And get an array of hashes so you know which address has which ip

Upvotes: 0

Related Questions