我正在阅读Module文档,但似乎无法理解它们的差异,哪些应该在哪里使用.
有什么eval不同exec?
Sinatra定义了许多似乎存在于当前范围内的方法,即不在类声明中.这些是在Sinatra gem中定义的.
我希望能够编写一个gem,它将创建一个我可以从全局范围调用的函数,例如
add_blog(:my_blog)
Run Code Online (Sandbox Code Playgroud)
然后,这将在全局范围内调用函数my_blog.
显然我可以使用add_blog函数monkeypatch gem中的Object类,但这似乎有点过分,因为它会扩展每个对象.
在下面的例子中,为什么我们说"k.send:hello"而不是"k.receive:hello"如果,如其他地方所述,k实际上是接收器?
它听起来像k是发送者,而不是接收器.
当我们说"k.send:你好"谁发送,如果不是k?
(你和我一样困惑吗?)
class Klass
def hello
"Hello!"
end
end
k = Klass.new
k.send :hello #=> "Hello"
k.hello #=> "Hello"
Run Code Online (Sandbox Code Playgroud) 有没有办法在Ruby中访问符号表中的所有内容?我希望能够序列化或以其他方式保存程序运行的当前状态.为此,我似乎需要能够遍历范围内的所有变量.
如果一切都是Ruby中的一个对象,甚至数学运算符都是应用于对象的方法,当我写:
puts "Hello world"
Run Code Online (Sandbox Code Playgroud)
方法是put,参数是"Hello world",但对象是什么?
鉴于此脚本
def hash
puts "why?"
end
x = {}
x[[1,2]] = 42
Run Code Online (Sandbox Code Playgroud)
它输出以下内容
why?
/tmp/a.rb:6:in `hash': no implicit conversion of nil into Integer (TypeError)
from /tmp/a.rb:6:in `<main>'
Run Code Online (Sandbox Code Playgroud)
在这种情况下,似乎hash脚本中定义的函数是重写的Array#hash.由于我的hash方法的返回值是nil而不是a Integer,它会抛出异常.以下脚本似乎证实了这一点
puts [1,2,3].hash
def hash
puts "why?"
end
puts [1,2,3].hash
Run Code Online (Sandbox Code Playgroud)
输出是
-4165381473644269435
why?
/tmp/b.rb:6:in `hash': no implicit conversion of nil into Integer (TypeError)
from /tmp/b.rb:6:in `<main>'
Run Code Online (Sandbox Code Playgroud)
我试着查看Ruby源代码,但无法弄清楚为什么会发生这种情况.这种行为是否有记录?
我输入hash了irb或Rails控制台,我可以看到它保留了一些随机值.我不知道它应该存在还是由某些宝石完成的.
这里:
hash # => -943824087729528496
Run Code Online (Sandbox Code Playgroud)
再试一次:
hash # => 3150408717325671348
Run Code Online (Sandbox Code Playgroud)
这是正常的吗?如果是这样,有什么用?或者这个值意味着什么?
好的,所以我查看了几本我的红宝石书并做了一些谷歌搜索无济于事.
Ruby中的main和initialize有什么区别?我见过使用的代码
class Blahblah
def main
# some logic here
end
# more methods...
end
Run Code Online (Sandbox Code Playgroud)
然后使用Blahblah.new调用它.
是不是仅为初始化保留新的?如果没有,那两者之间有什么区别?
我听说"Ruby是纯粹的OOP语言","Ruby中的所有东西都是对象".如果是这样,为什么我们有这两种情况呢?
puts并print处理它.根据OOP规则,对象的方法是应该操纵它的状态的方法.任何人都可以解释这两种情况如何符合"Ruby是纯OOP语言"这一短语吗?