Last active
September 8, 2017 08:51
-
-
Save KevinSia/1c82b8a32f79722fa968c16dac4113ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def triangle_up(num, char) | |
1.upto(num) { |i| puts char * i } | |
end | |
def triangle_down(num, char) | |
num.downto(1) { |i| puts char * i } | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## using for loop | |
def triangle_up(num, char) | |
for i in 1..num | |
puts char * i | |
end | |
end | |
def triangle_down(num, char) | |
# for loops cant go backwards | |
# eg. you can't do `for i in 5..1` | |
for i in 0..(num - 1) | |
puts char * (num - i) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## using until loop | |
def triangle_up(num, char) | |
i = 0 | |
until i > num | |
puts char * i | |
i += 1 | |
end | |
end | |
def triangle_down(num, char) | |
i = num | |
until i == 0 | |
puts char * i | |
i -= 1 | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## using while loop | |
def triangle_up(num, char) | |
i = 0 | |
while i <= num | |
puts char * i | |
i = i + 1 # or i += 1 | |
end | |
end | |
def triangle_down(num, char) | |
i = num | |
while i > 0 | |
puts char * i | |
i = i - 1 # or i -= 1 | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# without using string multiplication | |
def triangle_up(num, char) | |
1.upto(num) do |i| | |
i.times do | |
print char | |
end | |
puts | |
end | |
end | |
def triangle_up(num, char) | |
num.downto(1) do |i| | |
i.times do | |
print char | |
end | |
puts | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment