我是Ruby新手(坦率地说,我刚开始学习它的乐趣,没有任何未来的计划),我注意到循环的奇怪行为。我认为我的问题来自于Ruby的机制知识的缺乏。Ruby循环创建空行
boysNames = ["Martin", "Lucas", "John"]
#class only for one method. I know it's not absolutely correct, but huh I'm just learning Ruby
class Human
def initialize(name)
@name = name;
end
String name = ""
def getName()
puts @name;
end
end
Array boys = []
#create objects
for x in boysNames
tempBoy = Human.new(x)
boys.push(tempBoy)
end
#output for class
puts "Method 1: for in loop \n"
for x in boys
puts x.getName()
end
puts "\nMethod 2: manual array[var] \n"
boys[0].getName()
boys[1].getName()
boys[2].getName()
puts "\nMethod 3: .each do \n"
boys.each do |i|
puts i.getName()
end
#output for Array
puts "Method 1: for in loop \n"
for x in boysNames
puts x
end
puts "\nMethod 2: manual array[var] \n"
puts boysNames[0]
puts boysNames[1]
puts boysNames[2]
puts "\nMethod 3: .each do \n"
boysNames.each do |i|
puts i
end
#loop through the boys array
puts "\nboys array: \n"
for x in boys
puts x
end
所以我的问题是:为什么当我遍历数组,一切都很好,当我遍历类,我的结果由换行符分?有没有我找不到的“隐形”物体?正如你所看到的,我的最后一个循环只能找到三个在内存中具有不同位置的对象。
如果答案中包含“如何工作”的解释,我会很高兴。
谢谢您提前;)
P.S.输出:
Method 1: for in loop
Martin
Lucas
John
Method 2: manual array[var]
Martin
Lucas
John
Method 3: .each do
Martin
Lucas
John
Method 1: for in loop
Martin
Lucas
John
Method 2: manual array[var]
Martin
Lucas
John
Method 3: .each do
Martin
Lucas
John
boys array:
#<Human:0x007f2a586db788>
#<Human:0x007f2a586db648>
#<Human:0x007f2a586db5d0>
P.S.S.我使用this为Ruby解释器/编译器(我听说,红宝石也可以被编译,所以...)
既然你在学习,我会指出你应该注意的一些编码风格。你不需要类型注释,比如'String name',只需要'name'。和'Array boys = []'一样,只需使用'boys = []'。而Ruby使用'snake_case'而不是'camelCase'。我总是喜欢用[this](https://github.com/bbatsov/ruby-style-guide)等社区驱动的最佳实践回购来更习惯地学习语言!希望能帮助到你。玩得开心学习Ruby,这是一种美妙的语言! –
谢谢你的建议。 '字符串名称'让我知道什么类型的数据是'名称'。当谈到代码优化时,我绝对同意你的看法 我不知道Ruby中的snake_case习惯。很高兴知道! – Thomas