file - Scope and Variable Resolution in Ruby Blocks -


there missing in following code.

hostnames =  [] ip_addrs  =  [] hw_addrs  =  []  file.open("/etc/dhcp/dhcpd.conf", "r").each_line |line|    unless line.match('#')                        # make sure line not commented     if line.match("host-name")         hostname = line.scan(/"([^"]*)"/)       # extract hostname     elsif line.match("fixed-address")         ip_addr = line.scan(/(\s*);/)           # extract ip addr     elsif line.match("ethernet")       hw_addr = line.scan(/(\s*);/)             # extract hw address     end   end    hostnames + hostname.to_a if hostname         # protect against `nil' values   ip_addrs  + ip_addr.to_a  if ip_addr          #  same   hw_addrs  + hw_addr.to_a  if hw_addr          #  same  end  puts hostnames.inspect                          # should list of hostnames... 

this should populate arrays values found in dhcpd.conf file. if print values inside file.open.each_line block complete list stdout. when try values outside of block empty arrays.

i think block generates copy of variables , works on those, don't passed out of block. i'm not sure how internals work, guess.

if want add array need use proper operator:

hostnames += hostname.to_a if hostname 

what you're doing creating temporary result , discarding it: a + b not permanent modification, a = + b is, short-hand a += b.

generally use << add single elements array, avoids creating new array , appends existing one. example:

hostnames << hostname if hostname 

that's sufficient. casting arrays concatenate them wasteful unless appending several values @ once.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -