更改数组

时间:2015-07-27 13:47:25

标签: arrays ruby

如何更改/编辑数组中的第n个字母,特别是每五个字母?我试图改变每五个字母的ASCII值。我正在努力弄清楚如何从我从my_string.split("")字符串转换的数组中获取每五个字母。我想使用索引,但如果不可能,可以采用其他方法。

我的代码:

puts "Please enter your name."
user_name = gets.chomp
puts "Please enter message you would like to encrypt"
user_input = gets.chomp
fname = "#{user_name}'s Encrypted File.txt"
file = File.open(fname, "w+")
file.puts "#{user_input}"
file.close
words = user_input.split("")
words = |w|
  new = w.ord + 10
  new.chr!
  puts new
  fname = "#{user_name}'s Encrypted File.txt"
file = File.open(fname, "w+")
file.puts "#{new}"
file.close
puts "This is the text after encryption:"
file = file.open ("#{user_name}'s Encrypted File".txt)
puts "Do you want to see your original message?"
puts "Press 'Y' for Yes, press 'N' for No"
if gets.chomp == "Y"
  original = file.open ("#{user_name}'s Encrypted File".txt)
  green = original.split("")
  green.step(5).each {|five|
  five = five.chr - 10
  five.ord!
  puts original}
end

3 个答案:

答案 0 :(得分:3)

通过'更改/编辑数组中的第n个字母'我假设你想要更改数组。我们将变更定义为字母。因此:

arr.map!.with_index { |letter, index| index % 5 == 0 ? letter.upcase : letter }

答案 1 :(得分:3)

给出一个字符串:

str = "abcdefghijklmnopqrstuvwxyz"

您可以使用Range作为字符串的索引:

(0..str.size) #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]

Range#step枚举范围内的每个n元素:

(0..str.size).step(5).to_a #=> [0, 5, 10, 15, 20, 25]

您可以传递一个块来更改每个n个字符:

(0..str.size).step(5) { |n| str[n] = str[n].upcase }

str #=> "AbcdeFghijKlmnoPqrstUvwxyZ"

答案 2 :(得分:1)

或者只触摸每个第5个字符:

s = "abcdefghijklmnopqrstuvwxyz"
n = s.length
i = 0
while i < n
  s[i] = s[i].upcase
  i += 5
end

这给出了

> s
 => "AbcdeFghijKlmnoPqrstUvwxyZ"
>