There are many different ways in ruby to write the same thing.
puts (if 1 then 2 else 3 end)
# => 2
puts 1 ? 2 : 3
# => 2
x = if 1 then 2 else 3 end
puts x
# => 2
This is a ternary operator. It's a different syntax for control flow.
result = true ? "true" : "false"
puts(result)
print ("What is your name? ")
name = gets().strip
name = name.length > 20 ? name.slice(0, 20) : name
puts(name)
When you want to do the same thing a fixed amount of times.
50.times { print("=") }
50.times do
print("=")
end
When you want to do something to each element of an array.
arr.each do |item|
puts (item)
end
When you want to do something to each element of an array and use the index.
arr.each_with_index do |item, index|
puts ("#{index}. #{item}")
end
When you don't have a fixed number of interations.
while (retry_count < PASSWORD_RETRY_LIMIT) && (!is_valid_password(password))
password = get_password()
end
Ruby comes with file handling. No gem required.
To display the lines in a file.
File.open("todo-list.txt").each do |line|
puts line
end
To append to a file.
File.open("todo-list.txt", "a") do |line|
line << "Buy milk\n"
line << "Put out garbage\n"
line << "Do laundry\n"
end
To overwrite a file.
File.open("todo-list.txt", "w") do |line|
line << "Buy milk\n"
line << "Put out garbage\n"
line << "Do laundry\n"
end
This is an example of reading in a CSV file, converting the rows to hashes and then pushing that data into an array.
require 'csv'
require 'pry'
csv_text = File.read('world-cities.csv')
csv = CSV.parse(csv_text, :headers => true)
cities = []
csv.each do |row|
row_data = row.to_hash
if ( row_data['country'] == 'Australia' && row_data['subcountry'] == 'Victoria')
puts row_data
cities << row_data
end
end
puts cities.length