Domanda

I am trying to assign an integer for 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 a string so I tried something like this...

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

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

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

I would greatly appreciate if someone could give me a hint on how to assign the other 4 remaining letters of each string as well so that the output would be something like:

=> ["ABCDE", "ABCDE"]
=> [12345, 12345]
È stato utile?

Soluzione

Convert each of the string in your new array to an array of chars then, convert each of the character back to their position in the alphabet like you are doing then concat 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"]

Altri suggerimenti

Here is the trick of doing in more Rubyish way :

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

You first need to look into the magic of #gsub from gsub(pattern) {|match| block } → new_str.

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $,$&, and$'` will be set appropriately. The value returned by the block will be substituted for the match on each call.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top