传递给每个代码块的代码块使用括号而不是’do’ – ‘end'(r
发布时间:2020-12-17 01:45:26 所属栏目:百科 来源:网络整理
导读:我最近开始学习 ruby,我知道你可以使用这两种语法的代码块.但我刚发现一个我不明白的案例: #my_hash is a hash in which the keys are strings and the values arrays,but dont think about the specifics fo the code#if I run my code like this,it works
我最近开始学习
ruby,我知道你可以使用这两种语法的代码块.但我刚发现一个我不明白的案例:
#my_hash is a hash in which the keys are strings and the values arrays,but dont think about the specifics fo the code #if I run my code like this,it works perfectly my_hash.each do |art| puts mystring.gsub(art[0]).each { art[1][rand(art[1].length) -1] } end #but if I use this,it prints "Enumerator" my_hash.each do |art| puts mystring.gsub(art[0]).each do art[1][rand(art[1].length) -1] end end 是因为你不能窝对端吗? 解决方法puts mystring.gsub(art[0]).each do art[1][rand(art[1].length) -1] end 在这里你调用了puts而不是parens,do … end指的是puts方法,它对一个块没有任何作用并打印mystring.gsub(art [0]).每个(带有一个Enumerator). 使用最近的方法调用{…}.变得丑陋,但你可以做到… …结束: puts(mystring.gsub(art[0]).each do art[1][rand(art[1].length) -1] end) 或者,更好的是,将结果放在变量中并打印变量: var = mystring.gsub(art[0]).each do art[1][rand(art[1].length) -1] end puts var 无论如何,每个都不会改变对象,它只是迭代并返回对象本身.你可能想要map方法,测试一下. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |