Bug #11828
closedObject#freeze grid-locks Ruby
Description
It seems safe to freeze most any class type in Ruby. But if you call Object.freeze
nothing from then on can be created in either class of method form.
Is this okay behavior to have in Ruby?
Object.freeze
class A
end
# => RuntimeError: can't modify frozen #<Class:Object>
def x
end
# => RuntimeError: can't modify frozen class
I noticed that Procs can still be defined.
prc = proc {|a| a+1}
prc.call(4)
# => 5
But all singleton instances are frozen.
Updated by shugo (Shugo Maeda) over 8 years ago
- Status changed from Open to Feedback
Daniel P. Clark wrote:
It seems safe to freeze most any class type in Ruby. But if you call
Object.freeze
nothing from then on can be created in either class of method form.Is this okay behavior to have in Ruby?
Object.freeze class A end # => RuntimeError: can't modify frozen #<Class:Object>
The above code tries to define the constant A
in Object
, so a RuntimeError is raised.
def x end # => RuntimeError: can't modify frozen class
The above code tries to define the method x
in Object
, so a RuntimeError is raised.
The following code avoiding such operations on Object
works correctly even if Object
is frozen:
a = Class.new {
def foo
puts "foo"
end
}
a.new.foo
But all singleton instances are frozen.
What does "all singleton instances" mean?
Updated by danielpclark (Daniel P. Clark) over 8 years ago
Thank you for your reply. I've found your explanation most helpful.
What does "all singleton instances" mean?
Object.freeze
Enumerable.singleton_class.tap {def a; end}
# => RuntimeError: can't modify frozen class
Kernel.singleton_class.tap {def a; end}
# => RuntimeError: can't modify frozen class
Enumerator::Lazy.singleton_class.tap {def a; end}
# => RuntimeError: can't modify frozen class
UPDATE: My mistake... I was using tap
wrong again. It appears singleton_class
is still modifiable.
Enumerator.tap {|i| def i.a; end}
# => Enumerator
Enumerator.respond_to? :a
# => true
I was wrong about my last statement.
Updated by shugo (Shugo Maeda) over 8 years ago
- Status changed from Feedback to Rejected
Daniel P. Clark wrote:
What does "all singleton instances" mean?
Object.freeze Enumerable.singleton_class.tap {def a; end} # => RuntimeError: can't modify frozen class Kernel.singleton_class.tap {def a; end} # => RuntimeError: can't modify frozen class Enumerator::Lazy.singleton_class.tap {def a; end} # => RuntimeError: can't modify frozen class
UPDATE: My mistake... I was using
tap
wrong again. It appearssingleton_class
is still modifiable.Enumerator.tap {|i| def i.a; end} # => Enumerator Enumerator.respond_to? :a # => true
I was wrong about my last statement.
Ah, I see. Thanks for your confirmation.
So I close this ticket.