lukaszkups
lukaszkups

Reputation: 5990

map integer values to chars in array

I've got a method that generates random strings:

def generate_letters(length)
    chars = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
    letters = ''
    length.times { |i| letters << chars[rand(chars.length)] }
    letters
  end

I want to map values to generated strings, e.g.(1): A = 1, B = 2, C = 3 , e.g.(2): if I generate ACB it equals to 132. Any suggestions?

Upvotes: 0

Views: 1337

Answers (2)

KL-7
KL-7

Reputation: 47668

You can use that for concatenating these values:

s = 'ACB'
puts s.chars.map{ |c| c.ord - 'A'.ord + 10 }.join.to_i
# => 101211

and to sum them instead use Enumerable#inject method (see docs, there are some nice examples):

s.chars.inject(0) { |r, c| r + (c.ord - 'A'.ord + 10) } # => 33

or Enumerable#sum if you're doing it inside Rails:

s.chars.sum { |c| c.ord - 'A'.ord + 10 } # => 33

Upvotes: 1

polvoazul
polvoazul

Reputation: 2538

How would you deal with the ambiguity for leters above 10 (J) ? For example, how would you differentiate between BKC=2113 and BAAC=2113?

Disregarding this problem you can do this:

def string_to_funny_number(str)
    number=''
    str.each_byte{|char_value| number << (1 + char_value - 'A'.ord).to_s}
    return number.to_i
end

This function will generate a correct int by concatenating each letter value (A=1,B=2,...) Beware that this function doesn't sanitize input, as i am assuming you are using it with output from other function.

Upvotes: 1

Related Questions