Search code examples
arraysrubydecimalpackunpack

How do I convert an array of decimal values to a MAC address in Ruby?


I have an array of strings, and each item is a base 10 decimal value which needs to be converted to base 16 equivalents:

Input:

a = ["23", "137", "44", "30", "38", "2"]

Output:

#=> ["17", "89", "2c", "1e", "26", "02"]

Ideally I need to what the array really represents, which is a 48 byte MAC address:

#=> "17892c1e2602" or "17:89:2c:1e:26:02"

I tried and failed with both pack and unpack and:

a.map { |i| i.to_s(16) }

results in ArgumentError: wrong number of arguments (1 for 0).

Any help with conversion would be appreciated.


Solution

  • a = ["23", "137", "44", "30", "38", "2"]
    
    a.map(&:to_i).map { |i| i.to_s(16).rjust(2, '0') }.join ':' 
    #=> "17:89:2c:1e:26:02"
    

    UPD As suggested by Cary in comments, there is no need in two subsequent maps:

    a.map { |s| s.to_i.to_s(16).rjust(2, '0') }.join ':' 
    #=> "17:89:2c:1e:26:02"