Dostęp do stałych klasy
Gdy mam:
class Foo
CONSTANT_NAME = ["a", "b", "c"]
...
end
Czy istnieje sposób dostępu za pomocą Foo::CONSTANT_NAME
Czy muszę stworzyć metodę klasy, aby uzyskać dostęp do wartości?
149
Author: Arslan Ali, 2011-06-21
4 answers
To co napisałeś powinno działać idealnie:
class Foo
CONSTANT_NAME = ["a", "b", "c"]
end
Foo::CONSTANT_NAME
# => ["a", "b", "c"]
252
Author: Dylan Markow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-21 15:09:44
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-21 15:09:44
Jeśli piszesz dodatkowy kod w swojej klasie, który zawiera stałą, możesz traktować go jak globalny.
class Foo
MY_CONSTANT = "hello"
def bar
MY_CONSTANT
end
end
Foo.new.bar #=> hello
Jeśli uzyskujesz dostęp do stałej poza klasą, przedrostek powinien zawierać nazwę klasy, a następnie dwa dwukropki
Foo::MY_CONSTANT #=> hello
44
Author: maček,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-16 07:07:05
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-16 07:07:05
Niektóre alternatywy:
class Foo
MY_CONSTANT = "hello"
end
Foo::MY_CONSTANT
# => "hello"
Foo.const_get :MY_CONSTANT
# => "hello"
x = Foo.new
x.class::MY_CONSTANT
# => "hello"
x.class.const_defined? :MY_CONSTANT
# => true
x.class.const_get :MY_CONSTANT
# => "hello"
44
Author: aidan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-03 00:24:26
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-03 00:24:26
Czy Jest jakiś sposób na dostęp
Foo::CONSTANT_NAME
?
Tak, jest:
Foo::CONSTANT_NAME
17
Author: Jörg W Mittag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-21 16:05:35
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-21 16:05:35