Assign an integer to multiple characters in a string

I am trying to assign an integer to multiple characters in a string.

def userinput(input)
  @user = input.upcase.delete('^A-Z').chars.each_slice(5).map(&:join)
end

=> userinput("This is test to convert multiple characters in a string")
=> ["THISI","STEST","TOCON", "VERTM", "ULTIP", "LECHA", "RACTE", "RSINA", "STRIN", "G"]

After getting this array, I want to assign an integer for each character in the string, so I tried something like this ...

=> @user.map {|ch| ch.ord - 'A'.ord + 1}

Unfortunately, I only get the corresponding alphabet integer for the first letter.

=> [20, 19, 20, 22, 21, 12, 18, 18, 19, 7]

I would really appreciate it if someone could give me a hint on how to assign the remaining 4 remaining letters of each line so that the result would be something like this:

=> ["ABCDE", "ABCDE"]
=> [12345, 12345]
+3
source share
2 answers

Convert each line in your new array to an array of characters, then convert each character to its position in the alphabet, as you do, then concatenate them into a string

@user = ["THISI","STEST","TOCON", "VERTM", "ULTIP", "LECHA", "RACTE", "RSINA", "STRIN", "G"]
@user.map(&:chars).map do |arr| 
  arr.inject("") do |str,ch| 
    str << (ch.ord - 'A'.ord + 1).to_s 
  end
end
 => ["2089199", "192051920", "201531514", "225182013", "211220916", "125381", "1813205", "18199141", "192018914", "7"]
+1
source

, :

@user = ["THISI","STEST","TOCON"]
@user.map { |s| s.gsub(/[a-z]/i) { |m| m.ord - 'A'.ord + 1 } }
# => ["2089199", "192051920", "201531514"]

#gsub gsub(pattern) {|match| block } → new_str.

, , $1, $2, $, $& , and $'` . , , .

0

All Articles