你如何在Ruby中使用全局变量或常量值? [英] How do you use global variables or constant values in Ruby?
问题描述
我有一个如下程式:
$ offset = Point.new(100,200);
def draw(point)
pointNew = $ offset + point;
drawAbsolute(point)
end
draw(Point.new(3,4));
使用 $ offset
似乎有点奇怪。
在C语言中,如果我定义了任何函数以外的东西,它就会自动成为一个全局变量。为什么在Ruby中它必须是 $ offset
但是不能是 offset
并且仍然是全局的?如果它是偏移
,那么它是一个本地?但本地到哪里,因为它感觉非常全球。
有没有更好的方法来编写上面的代码?使用 $ offset
起初看起来有点难看。
<更新:我可以把这个偏移量放在一个
class
定义中,但是如果两个或几个类需要使用这个常量呢?在这种情况下,我还需要定义 $ offset
?你需要认识的一件事是在Ruby中,一切都是一个对象。鉴于此,如果您没有在 Module
或 Class
内定义您的方法,Ruby会将其放在 Object
class。因此,您的代码将在本地位于 Object
作用域。
面向对象编程的典型方法是封装所有类中的逻辑:
class Point
attr_accessor:x,:y
#如果我们不指定坐标,我们从0开始。
def initialize(x = 0,y = 0)
#请注意,`@`表示实例变量。
@x = x
@y = y
end
#这里我们覆盖`+'运算符。
def +(point)
Point.new(self.x + point.x,self.y + point.y)
end
#在这里我们绘制重点。
def draw(offset = nil)
如果offset.nil?
new_point = self
else
new_point = self + offset
end
new_point.draw_absolute
end
def draw_absolute
putsx:#{self.x},y:#{self.y}
end
end
first_point = Point.new(100,200)
second_point = Point.new(3,4)
second_point.draw(first_point)
希望澄清一下。
I have a program that looks like:
$offset = Point.new(100, 200);
def draw(point)
pointNew = $offset + point;
drawAbsolute(point)
end
draw(Point.new(3, 4));
the use of $offset
seems a bit weird.
In C, if I define something outside of any function, it is a global variable automatically. Why in Ruby does it have to be $offset
but cannot be offset
and still be global? If it is offset
, then it is a local? But local to where, because it feels very much global.
Are there better ways to write the code above? The use of $offset
may seem a bit ugly at first.
Update: I can put this offset inside a class
definition, but what if two or several classes need to use this constant? In this case do I still need to define an $offset
?
One thing you need to realize is in Ruby everything is an object. Given that, if you don't define your methods within Module
or Class
, Ruby will put it within the Object
class. So, your code will be local to the Object
scope.
A typical approach on Object Oriented Programming is encapsulate all logic within a class:
class Point
attr_accessor :x, :y
# If we don't specify coordinates, we start at 0.
def initialize(x = 0, y = 0)
# Notice that `@` indicates instance variables.
@x = x
@y = y
end
# Here we override the `+' operator.
def +(point)
Point.new(self.x + point.x, self.y + point.y)
end
# Here we draw the point.
def draw(offset = nil)
if offset.nil?
new_point = self
else
new_point = self + offset
end
new_point.draw_absolute
end
def draw_absolute
puts "x: #{self.x}, y: #{self.y}"
end
end
first_point = Point.new(100, 200)
second_point = Point.new(3, 4)
second_point.draw(first_point)
Hope this clarifies a bit.
这篇关于你如何在Ruby中使用全局变量或常量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!