Peter
Peter

Reputation: 759

Return string from multiple array items

I have multiple arrays which have code string items in them. I need to match the code from a given string and then return a class name from the matched array.

Might be better if I show you what I've got. So below are the arrays and underneath this is the string I need to return if the given string matches an item from within the array. So lets say I send a string of '329' this should return 'ss4' as a string:

['392', '227', '179', '176']
= 'ss1'

['389', '386']
= 'ss2'

['371', '338', '335']
= 'ss3'

['368', '350', '332', '329', '323', '185', '182']
= 'ss4'

I need to know what would be the best approach for this. I could create a helper method and have an array for each code block and then check each array to see if the given string code is contained and then return the string, which could be ss1 or ss4. Is this a good idea?

Upvotes: 2

Views: 243

Answers (5)

PinnyM
PinnyM

Reputation: 35541

The most efficient approach would be to generate a translator hash once that can perform the lookup super fast:

CODES = {
  ss1: ['392', '227', '179', '176'],
  ss2: ['389', '386'],
  ss3: ['371', '338', '335'],
  ss4: ['368', '350', '332', '329', '323', '185', '182']
}

translator = CODES.each_with_object({}){|(s, a), m| a.each{|n| m[n] = s.to_s}}

Now you can simply do:

translator['329']
=> "ss4"
translator['389']
=> "ss2"

Upvotes: 5

d_ethier
d_ethier

Reputation: 3911

I'd recommend joining all the arrays into a multi-dimensional hash and then searching that.

a1 = ['395']
a2 = ['392', '227', '179', '176']

h = { a1: a1, a2: a2 }
h.select {|a, v| a if v.include?('392') }.keys.first.to_s

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118299

h = {:ss1 => [395],:ss2 => [392, 227, 179, 176] }
h.key(h.values.find{|x| x.include? "392".to_i})
#=> :ss2

Upvotes: 0

fotanus
fotanus

Reputation: 20126

def code_to_string(code)
  if [395].include? code
    "ss1"
  elsif [392, 227, 179, 176].include? code
    "ss2"
  # and so on
end

Note that the codes are integers. to match with a string code, use %w(392 227 179).include? instead of the array

Upvotes: 1

Wally Altman
Wally Altman

Reputation: 3545

Here's one solution you could try:

CODE_LOOKUP = {
  [395] => 'ss1',
  [392, 227, 179, 176] => 'ss2',
  [389, 386] => 'ss3'
  # etc
}

def lookup_code(code)
  CODE_LOOKUP.each do |codes_to_test, result|
    return result if codes_to_test.include?(code)
  end
end

lookup_code(395)
# => "ss1"

lookup_code(179)
# => "ss2"

Upvotes: 0

Related Questions