新的红宝石,穿上你的新手套.
以下两个片段之间是否有任何区别(模糊或实用)?
my_array = [:uno, :dos, :tres]
my_array.each { |item|
puts item
}
my_array = [:uno, :dos, :tres]
my_array.each do |item|
puts item
end
Run Code Online (Sandbox Code Playgroud)
我意识到括号语法允许你将块放在一行上
my_array.each { |item| puts item }
Run Code Online (Sandbox Code Playgroud)
但除此之外是否有任何令人信服的理由使用一种语法而不是另一种语法?
哪种款式首选?一个与另一个有充分的理由吗?
提前致谢!
1) cmds.each do |cmd|
end
2) cmds.each { |cmd|
}
Run Code Online (Sandbox Code Playgroud)
示例代码:
cmds = [ "create", "update", "list", "help" ]
# Block style one
#
cmds.each do |cmd|
puts "loop1, cmd: #{cmd}"
end
# Block style two
#
cmds.each { |cmd|
puts "loop2, cmd: #{cmd}"
}
Run Code Online (Sandbox Code Playgroud) 我最近开始学习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
Run Code Online (Sandbox Code Playgroud)
是因为你不能窝对端对吗?我使用的是1.9
如果我有课:
class KlassWithSecret
def initialize
@secret = 99
end
end
Run Code Online (Sandbox Code Playgroud)
并运行:
puts KlassWithSecret.new.instance_eval { @secret }
Run Code Online (Sandbox Code Playgroud)
它打印99,但如果我运行:
puts KlassWithSecret.new.instance_eval do
@secret
end
Run Code Online (Sandbox Code Playgroud)
它返回一个错误: `instance_eval': wrong number of arguments (0 for 1..3) (ArgumentError)
为什么我不能使用do/end块instance_eval?
PS我正在使用Ruby 2.1.0.