简体   繁体   中英

ruby add values to string separated by comma except the first element

    device_target = ["3001", "3002", "3003"]
    devices = ",kv1101="
    device_target.map {|d|
      case d
        when "30000" #desktop
          devices << ":9"
        when "30001" # smartphone
          devices << ":3:4:6:8"        
        when "30002" #tablet
          devices << ":2:5:7"
        when "30003" #feature_phone
          devices << ":1"
      end

My target is to get devices = "kv1101=3:4:6:8:2:5:7:1" . But, how can I avoid this colon : from the first entry? The order doesn't matter.

Store the values in an array and then use the join method:

devices = ",kv1101="
my_devices = []
device_target.map {|d|
  case d
    when "30000" #desktop
      my_devices << "9"
    when "30001" # smartphone
      my_devices += ["3","4","6","8"]
    when "30002" #tablet
      my_devices += ["2","5","7"]
    when "30003" #feature_phone
      my_devices << "1"
  end}
devices << my_devices.join(":")

Similar to Fer's answer , but using flat_map and its return value:

device_target = ['30001', '30002', '30003']
devices = ',kv1101='
devices << device_target.flat_map { |device|
             case device
             when '30000' then 9            # desktop
             when '30001' then [3, 4, 6, 8] # smartphone
             when '30002' then [2, 5, 7]    # tablet
             when '30003' then 1            # feature_phone
             end
           }.join(':')

devices #=> ",kv1101=3:4:6:8:2:5:7:1"

Or using a lookup table as suggested by tadman :

device_target = ['30001', '30002', '30003']
device_map = {
  '30000' => 9,            # desktop
  '30001' => [3, 4, 6, 8], # smartphone
  '30002' => [2, 5, 7],    # tablet
  '30003' => 1             # feature_phone
}

devices = ',kv1101='
devices << device_target.flat_map { |d| device_map[d] }.join(':')

try this out:

"kv1101=:3:4:6:8:2:5:7:1".sub(/:/, "")
=> "kv1101=3:4:6:8:2:5:7:1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM