我被教过用声明我的实例变量def initialize。我一直觉得我只能在我的initialize方法中声明实例变量。
但是,我@foo在initialize方法之外声明了一个实例变量,并使其按预期工作:
class FooBar
def initialize(bar)
@bar = bar
end
def foo_as_instance_var
@foo = @bar.split(' ')
@foo
end
end
x = "something wicked this way comes"
y = FooBar.new(x)
puts y.foo_as_instance_var
Run Code Online (Sandbox Code Playgroud)
为什么我可以在initialize方法外部声明实例变量?由于我可以在任何方法中声明实例变量,因此关于在哪里声明实例变量(即在中声明它们initialize)是否应该遵循最佳实践规则?
我对以下几点感到满意:
def some_def(foo, &block)
puts "block utilized below"
block.call(foo)
end
def some_other_def(bar)
puts "using yield below"
yield bar
puts "and back into the method"
end
Run Code Online (Sandbox Code Playgroud)
所以我学会了将块(和过程)与yield关键字分开。
但是,我遇到了以下代码:
# ./open_file.rb
class File
def self.open(name, mode, &block)
file = new(name, mode)
return file unless block_given?
yield(file)
ensure
file.close
end
end
Run Code Online (Sandbox Code Playgroud)
&block当我在 irb 中执行此代码时,参数似乎并不重要:
irb -r ./file.open.rb
Run Code Online (Sandbox Code Playgroud)
并做类似的事情:
File.open('foo.txt','r') {|f| puts f}
Run Code Online (Sandbox Code Playgroud)
通过 in呈现&block为可选block_given?:
return file unless block_given?
Run Code Online (Sandbox Code Playgroud)