2017-04-04 29 views
0

我有以下幾行代碼來創建一個IP地址陣列,而我只打印出一個匹配模式的代碼。以零格式打印紅寶石陣列

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

我想接着寫該IP地址這樣

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

輸出的配置文件:

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

我怎麼能正確寫這個值到一個文件,而不引號和括號?

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

我試過gsubbing他們出來,但那不適合我。

+2

'綁定「#{ip_address.first}:22002 SSL CRT /等/ SSL /證書/通配符。 example.com.pem「' – mudasobwa

+0

工作感謝你! 我能夠讓#{puts ip_address}在irb中工作,但實際上並沒有那麼奇怪。 –

+0

@Brando__您的匹配代碼可能可以改進。你想要選擇哪個IP地址? – Stefan

回答

4

由於grep返回一個數組,因此您將得到「引號和括號」。爲了解決這個問題,你既可以打印單個元素:(見mudasobwa's comment

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

或者你可以修改代碼,只返回第一個地址匹配模式:

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

,並通過打印:

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

我總是想在10.0.128|129|0.*形式的地址。實際上我正在做的是這個作爲我的正則表達式。 grep(/10.0.(128|129|0).*/)

你必須逃脫點(\.)或把它們放在一個字符類([.])。否則,單個.將匹配任何字符。此外,您還應該匹配字符串的開始(^)和結束($)以避免匹配210.0.0.1。更堅實的正則表達式看起來是這樣的:

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

另外,還有Ruby的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