-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloops.rb
More file actions
56 lines (43 loc) · 1.17 KB
/
Copy pathloops.rb
File metadata and controls
56 lines (43 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Loops
# In ruby, we have several ways to create loops. Here are some of the most common ones:
# 1. `while` loop
# while loops is used to execute a block of code as long as a specified condition is true.
i = 0
while i < 5
puts i
i += 1
end
# 2. `until` loop
# until loops is used to execute a block of code as long as a specified condition is false.
i = 0
until i >= 5
puts i
i += 1
end
# 3. `for` loop
# for loops is used to iterate that we know how much times we want to execute a block of code.
# we can use data collection like array or range to iterate over.
# use range
for i in 0..4
puts i
end
# use array
fruits = ["apple", "banana", "cherry"]
for fruit in fruits
puts fruit
end
# 4. `each` loop
# each loops is used to iterate over a collection of items, such as an array or a hash.
# use array
[0, 1, 2, 3, 4].each do |i|
puts i
end
# use hash
person = { name: "John", age: 30, city: "New York" }
person.each_pair { |key, value| puts "#{key}: #{value}" }
# 5. `times` loop
# times loops is used to execute a block of code a specified number of times.
5.times do |i|
puts i
end
# For more methods and details, you can refer to the official Ruby documentation.