ruby新手问一个简单的问题,看不懂。

防空洞 2009-09-11 07:09:08
# Linked list example
class MyElem
# object initializer called from Class#new
def initialize(item)
# @variables are instance variable, no declaration needed
@data = item
@succ = nil
end

def data
@data
end

def succ
@succ
end

# the method invoked by ``obj.data = val''
def succ=(new)
@succ = new
end
end

class MyList
def add_to_list(obj)
elt = MyElem.new(obj)
if @head
@tail.succ = elt
else
@head = elt
end
@tail = elt
end

def each
elt = @head
while elt
yield elt
elt = elt.succ
end
end

# the method to convert object into string.
# redefining this will affect print.
def to_s
str = "<MyList:\n";
for elt in self
# short form of ``str = str + elt.data.to_s + "\n"''
str += elt.data.to_s + "\n"
end
str += ">"
str
end
end

class Point
def initialize(x, y)
@x = x; @y = y
self
end

def to_s
sprintf("%d@%d", @x, @y)
end
end

# global variable name starts with `$'.
$list1 = MyList.new
$list1.add_to_list(10)
$list1.add_to_list(20)
$list1.add_to_list(Point.new(2, 3))
$list1.add_to_list(Point.new(4, 5))
$list2 = MyList.new
$list2.add_to_list(20)
$list2.add_to_list(Point.new(4, 5))
$list2.add_to_list($list1)

# parenthesises around method arguments can be ommitted unless ambiguous.
print "list1:\n", $list1, "\n"
print "list2:\n", $list2, "\n"


请问MyList的dd_to_list(obj)如何理解
...全文
125 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
lliuxingyu 2009-10-01
  • 打赏
  • 举报
回复
菜菜,不懂!
kunhua15 2009-09-12
  • 打赏
  • 举报
回复
这样也可以?不是吧
peswe 2009-09-12
  • 打赏
  • 举报
回复

def add_to_list(obj)
elt = MyElem.new(obj)
if @head
@tail.succ = elt
else
@head = elt
end
@tail = elt
end

注意上面添加的是MyElem的实例对象,清楚了这点,就不难理解了
MyElem的实例对象都有data和succ方法,其中succ指向下一个元素,这样便可以串起来了
wuguanlin 2009-09-12
  • 打赏
  • 举报
回复
$list1 = MyList.new
$list1.add_to_list(10)
$list1.add_to_list(20)
$list1.add_to_list(Point.new(2, 3))
$list1.add_to_list(Point.new(4, 5))
$list2 = MyList.new
$list2.add_to_list(20)
$list2.add_to_list(Point.new(4, 5))
$list2.add_to_list($list1)
======================
这里不是在不停的加入元素吗?
防空洞 2009-09-11
  • 打赏
  • 举报
回复
只是这个方法怎么实现的linked list啊,元素能不停地往里加。
wuguanlin 2009-09-11
  • 打赏
  • 举报
回复
在MyList类里加了一个dd_to_list()方法

2,763

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ruby/Rails
社区管理员
  • Ruby/Rails社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧