3
    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.

3
  • 3
    Please provide valid input and output. The code can't produce "9:3:4:6:8:2". Commented Oct 6, 2014 at 13:00
  • 3
    I am sure it is just a typo but your "targets" are 3001,3002,3003 so 2 things one there is no 3000 and 2 your case statement will never work since d will never be in 30000,30001,30002,30003 Commented Oct 6, 2014 at 13:09
  • If any of the answers were helpful to you, consider selecting the one you valued most. Commented Nov 7, 2014 at 22:00

3 Answers 3

7

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(":")
Sign up to request clarification or add additional context in comments.

Comments

6

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(':')

2 Comments

flat_map does a great job in this case. Could be even better if instead of a rigid case statement it was a lookup table using a Hash.
A variant of #2: ",kv1101="+device_map.values_at(*device_target).flatten.join(?:).
-1

try this out:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.