开发者

Why ENV behave like a hash, but it's an Object class

Am I right to consider ENV a Hash

ENV['HOME']

=>开发者_如何学Go;'/Users/yozloy'

But

ENV.class

#=>Object


It implements most of the Hash methods but apparently a few are missing:

[:default, :default=, :default_proc, :default_proc=, :merge!, :merge, :flatten, :compare_by_identity, :compare_by_identity?]

Most of these you'd never think to use, but merge and flatten could be useful.

Remember that ENV isn't exactly a Hash, but a wrapper around the environment variables and the associated methods for retrieving and setting them.


CRuby sources tell you in hash.c

envtbl = rb_obj_alloc(rb_cObject);
rb_extend_object(envtbl, rb_mEnumerable);
...
/*
 * ENV is a Hash-like accessor for environment variables.
 *
 * See ENV (the class) for more details.
 */
rb_define_global_const("ENV", envtbl);

So although it is a plain object, envtbl can be treated like a Hash, although some methods are missing as stated by tadman.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜