From 22ce345b9bccb98b168de8a17e5c2b64b4a9ce7b Mon Sep 17 00:00:00 2001 From: Chanon18820 Date: Wed, 26 Nov 2025 09:14:35 +0700 Subject: [PATCH] finish finish --- lib/ruby_intro.rb | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/lib/ruby_intro.rb b/lib/ruby_intro.rb index c76ef193..d692a191 100644 --- a/lib/ruby_intro.rb +++ b/lib/ruby_intro.rb @@ -1,35 +1,60 @@ # When done, submit this entire file to the autograder. +# When done, submit this entire file to the autograder. + # Part 1 def sum(arr) - # YOUR CODE HERE + arr.reduce(0) { |acc, x| acc + x } + end def max_2_sum(arr) - # YOUR CODE HERE + return 0 if arr.empty? + return arr[0] if arr.length == 1 + + sorted = arr.sort.reverse + sorted[0] + sorted[1] end def sum_to_n?(arr, n) - # YOUR CODE HERE + return false if arr.length < 2 + + seen = {} + arr.each do |num| + return true if seen[n - num] + seen[num] = true end # Part 2 def hello(name) - # YOUR CODE HERE + "Hello, #{name}" end def starts_with_consonant?(s) - # YOUR CODE HERE + return false if s.nil? || s.empty? + /^[b-df-hj-np-tv-z]/i.match?(s) end def binary_multiple_of_4?(s) - # YOUR CODE HERE + return false unless /^[01]+$/.match?(s) + s.to_i(2) % 4 == 0 end # Part 3 class BookInStock - # YOUR CODE HERE + attr_reader :isbn, :price + attr_writer :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