# 1. Create a range that includes the end using new method. r = Range.new(1, 5) # 2. Shortcut to create a range that includes the end. r = 1..5
# Create Range object with short method. r = 1..5 # Create Range object with long method. s = Range.new(1, 5) print s.begin, "\n" # Returns 1. print s.end, "\n" # Returns 5. print s.includes?(3), "\n" # Returns true. print s.includes?(8), "\n" # Returns false. print s == r, "\n" # Returns true. print s == (2..8), "\n" # Returns false.
vm = VendingMachine.new
(1..6).each do |i|
(1..3).each do |j|
vm.deposit_quarter
end
vm.select_candy
end
Pay particular attention to Questions 8 and 9. Similar questions will be on the final exam.
a = [ ] or a = Array.new
a = ["a", "bc", "efg", "hijk"]
print "1#{a[1]}2#{a[3]}3#{a[5]}\n"
Ans:
1bc2hijk3
b = [56, 43, 11, 26, 98, 30]
# Problem 14a.
s = 0.0
b.each do |x|
s += x
end
print s / b.length
Ans: It computes the average of the array items: 264.
# Problem 14b.
b.each do |y|
if y > 50
print y, " "
end
end
Ans: It prints all the values greater than 50:
56
98
# Problem 14c.
m = -1000
b.each do |n|
if n > m
m = n
end
end
print m
Ans: m is the running maximum. Each loop of the for statement checks if n
is greater than the current running max m. If it is, m is updated.
m contains the maximum value at the end of the for loop:
98
# Problem 14d.
c = Array.new
b.each to |x|
c << x * 5280
end
print c
Ans: It creates a new array with the values in the array a converted
from miles to feet:
[295680, 227040, 58080, 137280, 517440, 158400]
Line 1
Line 2
...
Line 999
Line 1000
# Ans: here is the view code: <Display 1000 Lines> <% for i in 1..1000 %> <p>Line <%= i %></p> <% end %>
# Problem 7a.
(1..3).each do |n|
(1..4).each do |m|
print "*"
end
end
print "\n"
Ans:
************
# Problem 7b.
(1..3).each do |n|
(1..4).each do |m|
print "*"
print "\n"
end
end
Ans:
*
*
*
*
*
*
*
*
*
*
*
*
# Problem 7c.
(1..3).each do |n|
(1..4).each do |m|
print "*"
end
print "\n"
end
Ans:
****
****
****
s = ["cat", "dog", "mouse"] t = "" s.each do |x| t = x + t end print t, "\n" Ans: mousedogcat
<p>The total number of students is <%= Student.count %>.</p>
<p>The number of woman students is
<%= Student.find_all_by_gender('F').count %>.</p>
<p>The number of sophomores is <%= Student.find_all_by_gender(2).count %>.</p>
<%= f.label :credit_card_type %><br /> <%= f.text_field :credit_card_type %><br />
<%= f.label :credit_card_type %><br />
<%= f.select :credit_card_type,
[['Discover', 'D'],
[['MasterCard', 'M'],
[['Visa', 'V']] %><br />
<%= f.label :credit_card_type %><br /> Discover <%= f.radio_button :credit_card_type, 'D', :checked => false %> MasterCard <%= f.radio_button :credit_card_type, 'M', :checked => false %> Visa <%= f.radio_button :credit_card_type, 'D', :checked => true %>