abc b768 4slots First Name _n_ hook&ladder numberOfCustomers number-of-customers PreferredCustomer an_extremely_long_variable_name_if_you_ask_me Answers: abc (legal) b768 (legal) 4slots (illegal, starts with a digit) First Name (illegal, can't have embedded space) _n_ (legal) hook&ladder (illegal, can't use &) numberOfCustomers (legal, but not recommended Ruby syntax) number-of-customers (illegal, can't use dash in variable name) PreferredCustomer (legal as a class name, which uses upper camel casing) an_extremely_long_variable_name_if_you_ask_me (legal, but should be shorter to be practical)
Arithmetic operators: + - * / Comparison operators: < > <= >= == != Assignment operator: =
print s, " ", t, " ", 23, "\n"puts prints a single string like this:
puts s + " " + t.to_sputs automatically adds "\n" at the end of the string, so it's not necessary to explicitly include it.
print Time.now.month
a = "Jeremy"
b = 342
print "My friend #{a} owes me $#{b}.\n"
print rand 11
employee_id = 1001 + rand 999
x = 5
if x + 2 > 9
a = "yes"
else
a = "no"
end
r = 17 % 3 print r, "\n"
c = 20
f = 9 * c / 5 + 32
print "The Fahrenheit temperature is #{f}\n"
print "Enter a Celsius temperature: "
input = STDIN.gets
c = input.chomp.to_i
f = 9 * c / 5 + 32
print "The Fahrenheit temperature is #{f}\n"
# Use the new method to create an empty array. # Use the << method to append items to the array. pets = Array.new pets << 'dog' pets << 'cat' pets << 'parrot' pets << 'goldfish' # Use the shortcut method: pets = ['dog', 'cat', 'parrot', 'goldfish'] # Use the new method with a multiplication factor: a = Array.new(3, 'dog')
# Example 1
a = [3, 4, 5, 6, 7]
a.each do |i|
puts i + 1
end
Output:
4
5
6
7
8
# Example 2
sum = 0
r = [3, 4, 5, 6, 7]
r.each do |i|
sum = sum + i
end
puts sum
Output:
25 (The sum of the numbers in the array.)
# Example 3
pets = ['fido', 'felix', 'jerry']
pets.each do |p|
puts "I love my pet " + p + "."
end
Output:
I love my pet fido.
I love my pet felix.
I love my pet jerry.
rake db:seedNow start the Rails console and load all of the records from the database into an array with
a = Person.allUse for..each statements or each methods to print the first and last names for all the grade records:
a.each do |g|
print "#{g.first} {g.last}\n"
end
a = Person.all