What is the purpose of NilClass, TrueClass and FalseClass?

NilClass , TrueClass and FalseClass having one instance each, namely nil , true and false , which are constants, what is the purpose of these classes? Why can't they be instances of the Object class, and all relevant methods are simply defined as singleton methods on nil , true and false ? A related question: why are they not defined as constants?

+6
source share
2 answers

He adheres to the idea that "everything is an object" and "objects specialize in the classes in which they are instances."

nil , true and false are all objects (and thus are instances of the class with methods). The imposition that they are 1) the only inhabitants of the corresponding type and 2) are immutable objects, allows you to optimize the implementation - and is it really not just one nil ?

Useful error message without specialization for values: x.class "just works."

 > > nil.foo > => #<NoMethodError: undefined method `foo' for nil:NilClass> 

I'm glad he said NilClass

This instance class approach also makes re-opening NilClass - for better or worse - as easy as it can be for other types.

At least with Ruby 1.9.2 it is not possible to reassign true , false or nil (Python 2.x allows reassignment of True / False, but not in Python 3.X). Note that since true/false/nil are not constants, they can be optimized in AST - or regardless of implementation - as “literal values” without constant searching.

 > > VERSION > => "1.9.2" > > true = false > => #<SyntaxError: Can't change the value of true> > > [].each {|true|} > => #<SyntaxError: Can't change the value of true> 

Happy coding.

+11
source

Ruby uses the “just take an object and add some singleton methods to it” approach:

 C:\Documents and Settings\a.grimm>irb irb(main):001:0> self.methods - Object.new.methods 

gives

[: public ,: private ,: include ,: context ,: conf ,: irb_quit ,: exit ,: quit ,: irb_print_working_workspace ,: irb_cwws ,: irb_pwws ,: cwws ,: pwws ,: irb_current_working_binding ,: irb_print_working_binding ,: irb_cb irb_pwb ,: irb_chws ,: irb_cws ,: chws ,: cws ,: irb_change_binding ,: irb_cb ,: cb ,: workspaces ,: irb_bindings ,: bindings ,: irb_pushws ,: pushws ,: irb_push_binding ,: irb_ppb, : popws ,: irb_pop_binding ,: irb_popb ,: popb ,: source ,: jobs ,: fg ,: kill ,: help ,: irb_exit ,: irb_context ,: install_alias_method ,: irb_current_working_workspace ,: irb_change_workspace ,: irb_workspp_bp_bop ,: irb_load ,: irb_require ,: irb_source ,: irb ,: irb_jobs ,: irb_fg ,: irb_kill ,: irb_help]

I do not know why they do not do this approach with true , false or nil . Perhaps because people need to understand these objects (according to pst's answer), while people do not need to understand the "main" (?) Object.

+1
source

Source: https://habr.com/ru/post/900868/


All Articles