Reputation: 1931
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.
Upvotes: 2
Views: 222
Reputation: 5942
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}]"
Upvotes: 1
Reputation: 374
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~
Upvotes: 0