0

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?

2
  • Sorry, how do you mean 'map'? Do you want to get number 132 base on generated string 'ACB' or you need smth else? Commented Dec 27, 2011 at 16:19
  • yes - basing on that example, if my method generate 'BAC' string I want to recognize it as 213 Commented Dec 27, 2011 at 16:22

2 Answers 2

1

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

5 Comments

it works! thanks, but could You describe, what each thing in Your code means? I want to understand it :)
ok, but wait! it doesn't work for all letters - e.g. K is 11th letter but it equals 1 :/ btw. if You can write that it will start counting from 10 (A = 10, B = 11, ... , Z = 35) it will be awesome!
Sorry, my mistake. What should, for example, KZ be converted to? 2035?
Updated the answer. Is that what you need now?
nothing - I've found description of methods which You've used, thanks!
1

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.

1 Comment

differentiate is not required in my case :) I want to add these numbers - e.g ABC = 1 + 2 + 3, AABA = 1 + 1 + 2 + 1 etc. during this transformation

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.