Search code examples
arraysrubyconfiguration-filesput

Printing a ruby array with zero formatting


I have the following bit of code to make an array of IP addresses and I only print out one that matches a pattern.

ip_address = node.network.interfaces.map { |p, f| f[:addresses].keys }.flatten.delete_if{|x| x =~ /(.*):(.*)/ }.grep(/127/)

I'm trying to then write that IP address to a config file like this

  bind "#{ip_address}:22002 ssl crt /etc/ssl/certs/wildcard.example.com.pem"

Output:

  bind ["127.0.0.1"]:22002 ssl crt /etc/ssl/certs/wildcard.example.com.pem

How could I properly write this value to a file without the quotes and brackets?

  bind 127.0.0.1:22002 ssl crt /etc/ssl/certs/wildcard.example.com.pem

I've tried gsubbing them out, but that's not working for me.


Solution

  • You get the "quotes and brackets" because grep returns an array. To fix it, you could either print a single element: (see mudasobwa's comment)

    bind "#{ip_address.first}:22002 ssl crt /etc/ssl/certs/wildcard.example.com.pem"
    

    Or you could change the code to return only the first address matching the pattern:

    ip_addresses = node.network.interfaces.flat_map { |_, f| f[:addresses].keys }
    ip_address = ip_addresses.find { |x| x !~ /(.*):(.*)/ && x =~ /127/ }
    

    and print it via:

    bind "#{ip_address}:22002 ssl crt /etc/ssl/certs/wildcard.example.com.pem"
    

    I always want the address in the form of 10.0.128|129|0.*. In reality what I'm doing is this as my regex. grep(/10.0.(128|129|0).*/)

    You have to escape the dots (\.) or put them in a character class ([.]). Otherwise, a single . will match any character. Furthermore you should also match the start (^) and end ($) of the string to avoid matching 210.0.0.1. A more solid Regexp could look like this:

    /^10\.0\.(128|129|0)\.\d{1,3}$/
    

    Alternatively, there's Ruby's IPAddr:

    require 'ipaddr'
    
    valid_ips = [
      IPAddr.new('10.0.0.0/24'),
      IPAddr.new('10.0.128.0/24'),
      IPAddr.new('10.0.129.0/24')
    ]
    
    valid_ips.any? { |net| net.include? '127.0.0.1' }  #=> false
    valid_ips.any? { |net| net.include? '10.0.128.1' } #=> true
    valid_ips.any? { |net| net.include? '8.8.8.8' }    #=> false