ruby入门_for_in

周超英
2023-12-01

针对数组和哈希表

看例子就可以了

people1 = ["Tom", "Marry", "Jack", "Kay"]
people2 = {"Tom"=>23, "Marry"=>22, "Jack"=>25, "Kay"=>20}
# ------------------------
for person in people1
  puts person
end
# ------------------------
for personInfo in people2
  # puts "name #{personInfo[0]} age #{personInfo[1]}"
  puts personInfo[0] + " : " + personInfo[1].to_s
end
# ------------------------
for name, age in people2
  # puts "name #{name} age #{age}"
  puts name + " : " + age.to_s
end

输出

Tom
Marry
Jack
Kay
Tom : 23
Kay : 20
Jack : 25
Marry : 22
Tom : 23
Kay : 20
Jack : 25
Marry : 22

 类似资料: