我撰寫了一個函式,它獲取所有具有奇數索引的元素,并將它們與給定字串中具有偶數索引的所有元素連接 n 次:
def encrypt(text,n)
while n > 0
n -= 1
str_array = text.split("")
even_values = str_array.select.with_index { |_, i| i.even? }
odd_values = str_array.select.with_index { |_, i| i.odd? }
text = (odd_values even_values).join
end
puts text
end
puts 'Type your message to encrypt:'
text = gets
puts 'Type number of times to run encryption:'
n = gets.to_i
encrypt(text,n)
問題是,如果輸入文本包含奇數個元素,該函式將回傳 2 行文本。同時,如果輸入文本的元素數是偶數,則輸出是我想要的 1 行文本。
輸入文本中包含 10 個元素的控制臺輸出:
Type your message to encrypt:
abcdefghij
Type number of times to run encryption:
1
bdfhjacegi
輸入文本中有 11 個元素的控制臺輸出:
Type your message to encrypt:
abcdefghijk
Type number of times to run encryption:
1
bdfhj
acegik
uj5u.com熱心網友回復:
為了n = 1
def doit(str)
enum = [false, true].cycle
str.each_char.partition { enum.next }.map(&:join).join
end
doit "abcdefghij"
#=> "bdfhjacegi"
doit "abcdefghijk"
#=> "bdfhjacegik"
為了n > 1
n.times.reduce(str) { |s,_| doit(s) }
例如:
4.times.reduce(str) { |s,_| doit(s) }
#=>"ejdichbgafk"
參見Enumerable#reduce (aka inject)
現在考慮由 執行的計算doit。
首先考慮使用Array#cycleenum方法創建的列舉器:
enum = [false, true].cycle
#=> #<Enumerator: [false, true]:cycle>
我們可以使用Enumerator#next方法來查看這個列舉enum器將生成??什么值:
enum.next
#=> false
enum.next
#=> true
enum.next
#=> false
... ad infinitum
現在讓我們使用Enumerator#rewind重置列舉器:
enum.rewind
#<Enumerator: [false, true]:cycle>
認為
str = "abcdefghijk"
然后
e = str.each_char
#=> #<Enumerator: "abcdefghijk":each_char>
我們可以將此列舉器轉換為陣列,以查看它將生成哪些元素。
e.to_a
#=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
繼續,
a = e.partition { enum.next }
#=> [["b", "d", "f", "h", "j"], ["a", "c", "e", "g", "i", "k"]]
b = a.map(&:join)
#=> ["bdfhj", "acegik"]
b.join
#=> "bdfhjacegik"
注意a.map(&:join)是 的簡寫a.map { |arr| arr.join }。
請參閱String#each_char、Enumerable#partition和Array#join。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/478566.html
上一篇:RubyOnRails 嘗試將JSON轉換為特定格式
下一篇:回傳哈希值等于的索引
