数组取幂

时间:2016-02-15 22:30:06

标签: ruby

我有一个字符串,例如

a = 'Thank you for your answer'

我需要从字符串中获取每个单词的长度,然后将它们提升到下一个单词的幂,例如:

result = ((((5**3)**3)**4)**6)

我该怎么做?

1 个答案:

答案 0 :(得分:4)

inject会:

s = 'Thank you for your answer'

s.split(/\s+/)
# => ["Thank", "you", "for", "your", "answer"]

s.split(/\s+/).map{|w| w.length}
# => [5, 3, 3, 4, 6]

s.split(/\s+/).map{|w| w.length}.inject(:**)
# => 9495567745759798747473242269561957154220965833619944966279779990829008230644811159033118931771413600093027632988162967109246892505325376987457275390625

((((5**3)**3)**4)**6)
# => 9495567745759798747473242269561957154220965833619944966279779990829008230644811159033118931771413600093027632988162967109246892505325376987457275390625