Project1
标题:
请问如何将数组转化为字符串
[打印本页]
作者:
ONEWateR
时间:
2011-6-25 22:33
标题:
请问如何将数组转化为字符串
本帖最后由 ONEWateR 于 2011-6-25 22:34 编辑
如题。
关于转化,如
a=[1,2,3,4,5]
转化后为
s = "[1,2,3,4,5]"
小弟在此先谢谢各位 -w- dsu_plus_rewardpost_czw
作者:
Wind2010
时间:
2011-6-25 23:08
class Array
def to_s
s = self.clone
for i in 0...s.size
s[i] = s[i].to_s
end
st = "["
for i in s
st += i
st += "," if s.index(i) != s.size-1
end
st += "]"
return st
end
end
p [1,2,3,4,5].to_s #=> "[1,2,3,4,5]"
复制代码
Wind2010于2011-6-25 23:08补充以下内容:
class Array
def to_s
s = self.clone
for i in 0...s.size
s[i] = s[i].to_s
end
st = "["
for i in s
st += i
st += "," if s.index(i) != s.size-1
end
st += "]"
return st
end
end
p [1,2,3,4,5].to_s #=> "[1,2,3,4,5]"
复制代码
作者:
enghao_lim
时间:
2011-6-26 00:03
本帖最后由 enghao_lim 于 2011-6-26 00:07 编辑
方式与楼上雷同,不过比较短些,迭代也应该比较少,没仔细比对。想不到更好的方式-==|||。
class Array
def to_string
string = "["
(0...self.size).each do |i|
string += self[i].to_s
if i != self.size-1
string += ","
end
end
string += "]"
return string
end
end
p [1,2,3,4,5,9].to_string
复制代码
作者:
灼眼的夏娜
时间:
2011-6-26 01:34
[1,2,3,4,5].inspect
欢迎光临 Project1 (https://rpg.blue/)
Powered by Discuz! X3.1