从Ruby中包含的文件中访问变量 [英] Accessing variables from included files in Ruby

查看:91
本文介绍了从Ruby中包含的文件中访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问包含文件中定义的变量?

How do you access variables which are defined in an included file?

# inc.rb
foo = "bar";


# main.rb
require 'inc.rb'
puts foo

# NameError: undefined local variable or method `foo' for main:Object


推荐答案

你无法访问它所定义的范围之外的本地 - 在这种情况下的文件。如果您想要跨越文件边界的变量,那么除了本地之外,还要做任何事情。 $ foo Foo @foo 一切正常。

You can't access a local outside of the scope it was defined in — the file in this case. If you want variables that cross file boundaries, make them anything but locals. $foo, Foo and @foo will all work.

如果你真的不想在符号上加上任何装饰(因为你不喜欢它的读取方式,也许),一个常见的黑客攻击只是将其定义为一种方法: def foo()barend

If you just really don't want to put any sort of decoration on the symbol (because you don't like the way it reads, maybe), a common hack is just to define it as a method: def foo() "bar" end.

这篇关于从Ruby中包含的文件中访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆