传递给每个代码块的代码块使用括号而不是’do’ – ‘end'(ruby)

传递给每个代码块的代码块使用括号而不是’do’ – ‘end'(ruby),第1张

概述我最近开始学习 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 w 我最近开始学习 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 perfectlymy_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]  endend

是因为你不能窝对端吗?
我使用的是1.9

解决方法
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]endputs var

无论如何,每个都不会改变对象,它只是迭代并返回对象本身.你可能想要map方法,测试一下.

总结

以上是内存溢出为你收集整理的传递给每个代码块的代码块使用括号而不是’do’ – ‘end'(ruby)全部内容,希望文章能够帮你解决传递给每个代码块的代码块使用括号而不是’do’ – ‘end'(ruby)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1247630.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存