Ruby学习笔记-循环与选择结构
一、循环结构
1.? ? for…in语句:
Ruby提供的for...in语句主要用于迭代数组和Hash对象中的元素,与其它语言的for语句有一定的差距,语法格式:
(1)使用for…in语句时,每次只能取出一个数组元素,而不能一次取出多个。
(2)当for循环的代码全在一行上时不能省略掉do,否则会报错; 只有当for循环的代码在多行上时才可以省略掉do;
2.? ?? ? Blocks:
在Ruby中有两种定义块的方法:
3.? ?? ? While语句:
这个和其它语言差别不大,没什么好说的,语法格式如下:
- case(i)
- ? ?? ???when 1: puts(“It’s Monday”)
- ? ?? ???when 2: puts(“It’s Tuesday”)
- ? ?? ???when 3: puts(“It’s Wednesday”)
- ? ?? ? when 4: puts(“It’s Thursday”)
- ? ?? ???when 5: puts(“It’s Friday”)
- ? ?? ???when (6..7): puts(“It’s the weekend!”)
- ? ?? ???else puts(“error”)
- end??
- ------------------or------------------------ ???
- case(i)
- ? ?? ???when 1
- ? ? ? ??? ? ? ??puts(“It’s Monday”)
- ? ?? ???when 2
- ? ? ? ??? ? ? ??puts(“It’s Tuesday”)
- ? ?? ???when 3?
- ? ? ? ??? ? ? ??puts(“It’s Wednesday”)
- ? ?? ???when 4
- ? ? ? ??? ? ? ??puts(“It’s Thursday”)
- ? ?? ???when 5?
- ? ? ? ??? ? ? ??puts(“It’s Friday”)
- ? ?? ???when (6..7)
- ? ? ? ??? ? ? ??puts(“It’s the weekend!”)
- ? ?? ???else
- ? ? ? ??? ? ? ??puts(“error”)
- end ?