传递给每个的代码块使用方括号但不使用“do"-“end"(ruby) [英] Code block passed to each works with brackets but not with 'do'-'end' (ruby)

查看:39
本文介绍了传递给每个的代码块使用方括号但不使用“do"-“end"(ruby)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习 ruby​​,我知道您可以使用具有这两种语法的代码块.但是我刚刚发现了一个我不明白的案例:

I recently started learning ruby, and I understood that you coud use code blocks with both of these syntaxes. But I just found a case which I dont understand:

#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

是因为你不能嵌套 do-end 对吗?我正在使用 1.9

Is it because you cant nest do-end pairs? I am using 1.9

推荐答案

puts mystring.gsub(art[0]).each do
  art[1][rand(art[1].length) -1]
end

这里你调用了没有括号的 putsdo ... end 指的是 puts 方法,它对块和打印 mystring.gsub(art[0]).each(带有一个 Enumerator).

Here you called puts without parens, the do ... end refers to the puts method, that does nothing with a block and prints mystring.gsub(art[0]).each (with is a Enumerator).

{ ... } 用最近的方法调用.变得丑陋,但你可以用 do ... end 做到:

The { ... } is called with the nearest method. Becomes ugly, but you can do it with do ... end:

puts(mystring.gsub(art[0]).each do
  art[1][rand(art[1].length) -1]
end)

或者,更好的是,将结果放入一个变量中并打印该变量:

Or, better, put the result in a variable and print the variable:

var = mystring.gsub(art[0]).each do
  art[1][rand(art[1].length) -1]
end
puts var

无论如何,each 不会改变对象,它只是迭代并返回对象本身.您可能需要 map 方法,请测试它.

Anyway, the each don't changes the object, it just iterate and returns the object itself. You may be wanting the map method, test it.

这篇关于传递给每个的代码块使用方括号但不使用“do"-“end"(ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆