hw-ruby-intro/lib/ruby_intro.rb

70 lines
975 B
Ruby

# When done, submit this entire file to the autograder.
# Part 1
def sum arr
nums=0
arr.each do |i|
nums=nums+i
end
return num
end
def max_2_sum arr
if arr.length==0
return 0;
elsif arr.length==1
return arr.first;
else
return (arr.sort!.pop)+(arr.sort!.pop);
end
end
def sum_to_n? arr, n
if arr.empty?
return ture if n==0
else
arr.combination(2).to_a.each do |pair|
if pair[0]+pair[1]==n
return ture
end
end
end
return false
end
# Part 2
def hello(name)
return "Hello, "+name
end
def starts_with_consonant? s
(s[0]=~/[bcdfghjklmnprstvwxyz]+/i)
end
def binary_multiple_of_4? s
if s=~/^[0-1]+$/
return s.to_i(2) % 4==0
end
return false
end
# Part 3
class BookInStock
attr_accessor :isbn,:price
def initialize isbn,price
raise ArgumentError if isbn.empty? || price<=0
@isbn=isbn
@price=price
end
def price_as_string
format("$%.2f",@price)
end
end