SO03112
SO03112

Reputation: 178

undefined method trying to match string

I'm getting an 'undefined method' error on the get_nums method below, and I can't figure out why. list_hostnames returns an array, but get_nums can't do anything with it. Could someone please point me in the right direction?

class Hostname
  attr_accessor :hostname, :domain_controller_ip, :username, :password, :hosts

  def initialize(hostname, domain_controller_ip, ad_username, ad_password)
    @domain_controller_ip = domain_controller_ip
    @ad_username = ad_username
    @ad_password = ad_password
    @hostname = hostname
    @hosts = []

  def list_hostnames
    a = Ldap.new(@domain_controller_ip, @ad_username, @ad_password)
    hostname = @hostname + "*"
    a.ldap_con.search(:base => a.treebase, :filter => a.filter('cn', hostname)) do |entry|
      self.hosts.push(entry.cn[0])
    end
    self.hosts.each do |x|
      p x
    end
  end

  def get_nums
    self.hosts.each do |x|
      i = x.match(/\d+$/)
      p i
    end
end
end

a = Hostname.new('prod-srv-1', '192.168.1.1', 'administrator', 'password')
b = a.list_hostnames
b.get_nums
end

Upvotes: 0

Views: 125

Answers (2)

Igor Drozdov
Igor Drozdov

Reputation: 15055

It seems, that you've been confused by indentation and didn't correctly close the methods by end.

I think that the following code is the correct version of the code you're trying to implement:

class Hostname
  attr_accessor :hostname, :domain_controller_ip, :username, :password, :hosts

  def initialize(hostname, domain_controller_ip, ad_username, ad_password)
    @domain_controller_ip = domain_controller_ip
    @ad_username = ad_username
    @ad_password = ad_password
    @hostname = hostname
    @hosts = []
  end

  def list_hostnames
    a = Ldap.new(@domain_controller_ip, @ad_username, @ad_password)
    hostname = @hostname + "*"
    a.ldap_con.search(:base => a.treebase, :filter => a.filter('cn', hostname)) do |entry|
      self.hosts.push(entry.cn[0])
    end
    self.hosts.each do |x|
      p x
    end

    self
  end

  def get_nums
    self.hosts.each do |x|
      i = x.match(/\d+$/)
      p i
    end
  end
end

a = Hostname.new('prod-srv-1', '192.168.1.1', 'administrator', 'password')
b = a.list_hostnames
b.get_nums

Upvotes: 3

Zach Tuttle
Zach Tuttle

Reputation: 2341

Since you have an attr_accessor defined for hosts, you don't need the self.hosts. You could just do:

hosts.each do |h|
  # code here
end

Upvotes: 0

Related Questions