2

I want to modify part of a string I have using Ruby.

The string is [x, y] where y is an integer that I want to change to its alphabetical letter. So say [1, 1] would become [1, A] and [1, 26] would become [1, Z].

Would a regular expression help me do this? or is there an easier way? I am not to strong with regular expressions, I am reading up on those now.

3
  • Looks like you have a string where you should have a tuple? Commented Aug 22, 2012 at 14:42
  • Well what I am doing is changing an index I have for excel cells. The gem I am using gives me the index as [1, 1], etc. I just want to change that to the column formats [1, A] Commented Aug 22, 2012 at 14:49
  • MS Excel can handle that: choose Tools->Options->General tab-> R1C1 reference style. Commented Aug 22, 2012 at 15:44

2 Answers 2

1

The shortest way I can think of is the following

string = "[1,1]"
array = string.chop.reverse.chop.reverse.split(',')
new_string="[#{array.first},#{(array.last.to_i+64).chr}]"
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe this helps:

Because we do not have an alphabet yet we can look up the position, create one. This is a range converted to an array so you don't need to specify it yourself.

alphabet = ("A".."Z").to_a

Then we try to get the integer/position out of the string:

string_to_match = "[1,5]"
/(\d+)\]$/.match(string_to_match)

Maybe the regexp can be improved, however for this example it is working. The first reference in the MatchData is holding the second integer in your "string_to_match". Or you can get it via "$1". Do not forget to convert it to an integer.

position_in_alphabet = $1.to_i

Also we need to remember that the index of arrays starts at 0 and not 1

position_in_alphabet -= 1

Finally, we can take a look which char we really get

char = alphabet[position_in_alphabet]

Example:

alphabet = ("A".."Z").to_a #=> ["A", "B", "C", ..*snip*.. "Y", "Z"]
string_to_match = "[1,5]" #=> "[1,5]"
/(\d+)\]$/.match(string_to_match) #=> #<MatchData "5]" 1:"5">
position_in_alphabet = $1.to_i #=> 5
position_in_alphabet -= 1 #=> 4
char = alphabet[position_in_alphabet] #=> "E"

Greetings~

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.