104 lines
1.5 KiB
Ruby
104 lines
1.5 KiB
Ruby
# When done, submit this entire file to the autograder.
|
|
|
|
# Part 1
|
|
|
|
def sum arr
|
|
# YOUR CODE HERE
|
|
sum = 0
|
|
arr.each do |i|
|
|
sum += i
|
|
end
|
|
return sum
|
|
end
|
|
|
|
def max_2_sum arr
|
|
# YOUR CODE HERE
|
|
if arr.size == 0
|
|
return 0
|
|
elsif arr.size == 1
|
|
return arr[0]
|
|
else
|
|
sum = 0
|
|
sum += arr.max
|
|
arr.delete_at arr.index(sum)
|
|
sum += arr.max
|
|
return sum
|
|
end
|
|
end
|
|
|
|
def sum_to_n? arr, n
|
|
# YOUR CODE HERE
|
|
if arr.size < 2
|
|
return false
|
|
end
|
|
arr.each_with_index do |first_number, i|
|
|
j = i + 1
|
|
while j < arr.size
|
|
if first_number + arr[j] == n
|
|
return true
|
|
end
|
|
j += 1
|
|
end
|
|
end
|
|
|
|
return false
|
|
end
|
|
|
|
# Part 2
|
|
|
|
def hello(name)
|
|
# YOUR CODE HERE
|
|
"Hello, " + name
|
|
end
|
|
|
|
def starts_with_consonant? s
|
|
# YOUR CODE HERE
|
|
if /^[^aeiouAEIOU]/ =~ s and /^[a-zA-Z]/ =~ s # 必须不能一以原因以原音字母开头,而且必须以字母开头
|
|
return true
|
|
end
|
|
return false
|
|
end
|
|
|
|
def binary_multiple_of_4? s
|
|
# YOUR CODE HERE
|
|
if /[^01]/ =~ s # 判断是否有效
|
|
return false
|
|
end
|
|
if s.size == 0
|
|
return false
|
|
end
|
|
if s.size == 1
|
|
return s == "0"
|
|
end
|
|
if s.size == 2
|
|
return s == "00"
|
|
end
|
|
if s[-2..-1].to_s.include?('1')
|
|
return false
|
|
else
|
|
return true
|
|
end
|
|
end
|
|
|
|
# Part 3
|
|
|
|
class BookInStock
|
|
# YOUR CODE HERE
|
|
|
|
def initialize(isbn, price)
|
|
if isbn.empty? or price <= 0
|
|
raise ArgumentError
|
|
end
|
|
@isbn = isbn
|
|
@price = price
|
|
end
|
|
|
|
attr_accessor :isbn
|
|
attr_accessor :price
|
|
|
|
def price_as_string
|
|
format('$%.2f', @price)
|
|
end
|
|
|
|
end
|