Ruby 文字小游戏:attitude==100

chenge · 2013年04月30日 · 最后由 chenge 回复于 2016年07月04日 · 3146 次阅读
def count(word)
    nc = {}
    ('a'..'z').each_with_index {|x, index| nc[x] = index + 1 }
    count = 0
    word.split(//).each { |x| count +=  nc[x] }
    word.upcase! if count==100
    "#{word} is #{count}"
end

def count2(word)
    nc = {}
    ('a'..'z').each_with_index { |x, index| nc[x] = index + 1 }
    count = word.split(//).map{ |x| nc[x] }.reduce(:+)
    word.upcase! if count==100
    "#{word} is #{count}"
end

p count('hardwork')
p count('knowledge')
p count('luck')
p count('love')
p count('money')
puts
p count2('attitude')
puts



#==》
"hardwork is 98"
"knowledge is 96"
"luck is 47"
"love is 54"
"money is 72"

"ATTITUDE is 100"

请帮忙改一下作业,word.split(//) 有没有更易读的写法?

word.downcase.each_char.collect(&:ord).inject(&:+) - 'a'.ord * word.size + word.size

#2 楼 @chenge, #1 楼 @doitian 👍
一举两得 😄

  1. 有知识:Array,String
  2. 有内涵:Hardwork,Knowledge,Luck,Love,Money,Attitude

def count3(word)
  word.downcase.each_char.map{|x|x.ord - 'a'.ord + 1}.inject(:+)
end

p count3('attitude')  

#3 楼 @zputee 今天看到微博,想到这个。你的这个改进不错。

#4 楼 @chenge

  • split(//) | each_char | each_with_index
  • redue(:+) | inject(&:+),
  • collect | map,
  • ord

这些方法放在一起练习,这个形式不错!


def count3(word)
  word.downcase.each_char.collect{|x|x.ord - 'a'.ord + 1}.reduce(:+)
end
p count3('attitude')  

前面的 nc={} 这一句,好像可以省了。 最近琢磨 ruby,咬文嚼字了。 😊

#6 楼 @zputee 不行的,你验证下。

#7 楼 @chenge 我搞错了,:-)

Proc 可以绑定环境变量。 反向不行,不能定义带出来。(block 不是嵌入呀) nc[x] = index 也不是赋值语句!!!🐻

.ord 在 1.8.7 里边用不了?

chenge Ruby 学习汇集,请推荐内容 提及了此话题。 07月04日 11:35
需要 登录 后方可回复, 如果你还没有账号请 注册新账号