Bug #11828
closed
Object#freeze grid-locks Ruby
Added by danielpclark (Daniel P. Clark) over 8 years ago.
Updated over 8 years ago.
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.
- 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?
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.
- 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 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.
Ah, I see. Thanks for your confirmation.
So I close this ticket.
Also available in: Atom
PDF
Like0
Like0Like0Like0