Ruby For Loop Number Ranges


I was starting to learn Ruby, and came across number ranges in a for loop. I discovered that there is an easy way to include or exclude the top boundary depending upon the number of periods that you use. Note that you can also use variables as either end of the range.

top_limit = 3
for i in 1..top_limit # inclusive of the top boundary
  puts i # 1 2 3

for j in 1...top_limit # doesn't include the top boundary
  puts j # 1 2
Tags: #Ruby Comments: Loading comment count... Author: Seth Westphal

How to Use a Stack Data Structure in Ruby


After more tinkering in Ruby, I came across the need to use the Stack data structure. To my surprise, one was nowhere to be found. However, I was even more surprised when I found out that the Stack operations are implemented by the standard Ruby Array class.

# initialization
stack =

# pushing an item onto the stack
stack << "item2"

# popping an item off the stack
top_item = stack.pop

# peeking at the top item
puts stack.last
puts stack[-1]

# checking if the stack is empty
puts stack.empty?

# checking the size of the stack
puts stack.size
puts stack.count
puts stack.length
Tags: #Ruby Comments: Loading comment count... Author: Seth Westphal