如果讨论或非常明显,请随意删除此主题.我来自C#背景,我打算学习Ruby.我读到的所有内容似乎都很有趣.但我对Ruby的这个基本哲学感到困惑,"有一种方法可以做一件事".有人可以提供2或3个简单的算术或字符串示例来明确这一点,例如它的语法或逻辑等.
谢谢
我最近开始学习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
puts [1,2,3].map do |x|
x + 1
end.inspect
Run Code Online (Sandbox Code Playgroud)
随着ruby 1.9.2的回归
<Enumerator:0x0000010086be50>
Run Code Online (Sandbox Code Playgroud)
红宝石1.8.7:
# 1
# 2
# 3
Run Code Online (Sandbox Code Playgroud)
分配变量......
x = [1,2,3].map do |x|
x + 1
end.inspect
puts x
Run Code Online (Sandbox Code Playgroud)
[2,3,4]
小胡子块按预期工作:
puts [1,2,3].map { |x| x + 1 }.inspect
Run Code Online (Sandbox Code Playgroud)
[2,3,4]
如果我有课:
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.
为什么:
test = [1, 1, 1].collect do |te|
te + 10
end
puts test
Run Code Online (Sandbox Code Playgroud)
有效,但不是:
puts test = [1, 1, 1].collect do |te|
te + 10
end
Run Code Online (Sandbox Code Playgroud)
然而这有效:
puts test = [1, 1, 1].collect { |te|
te + 10
}
Run Code Online (Sandbox Code Playgroud)
对于我不知道的块,do/end构造和{}构造之间是否存在差异?
我对传球有一点疑问.
def a_method(a, b)
a + yield(a, b)
end
Run Code Online (Sandbox Code Playgroud)
这很好用.
k = a_method(1, 2) do |x, y|
(x + y) * 3
end
puts k
Run Code Online (Sandbox Code Playgroud)
但这不起作用.
puts a_method(1, 2) do |x, y|
(x + y) * 3
end
# LocalJumpError: no block given (yield)
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释这个吗?
谢谢.Paolo Perrotta从Metaprogramming Ruby中获取的示例.好书.
我有代码:
i = 1
while i < 11
do
end
print "#{i}"
i = i + 1
end
Run Code Online (Sandbox Code Playgroud)
这导致错误"在线do:语法错误,意外的keyword_do_block".如果我移动do之后while这样while i < 11 do,错误消失.它不应该发生,因为do它像一个开放的大括号{.为什么这是一个错误?