First 16 rows of rb
| uuidstring | contentstring | content_formatstring | raw_contentstring | taskstring | analysisstring | solutionstring | teststring | full_contentstring | full_content_formatstring |
|---|---|---|---|---|---|---|---|---|---|
| 4875d26b-cb85-440e-a7be-166cf4f6efe5 | =begin Given a binary tree where each node contains an integer value, write a Ruby method that returns the tree mirrored horizontally (i.e., inverted) by swapping every node's left and right children. The method should accept the root node (of type `TreeNode` with attributes `val… | code comment | # Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val = 0, left = nil, right = nil) # @val = val # @left = left # @right = right # end # end # @param {TreeNode} root # @return {TreeNode} … |
| Given a binary tree where each node contains an integer value, write a Ruby method that returns the tree mirrored horizontally (i.e., inverted) by swapping every node's left and right children. The method should accept the root node (of type `TreeNode` with attributes `val`, `lef… |
| The core algorithm is a recursive or iterative traversal that swaps left and right children at every node. The recursive approach (depth-first) starts at the root: if the root is nil, return nil. Otherwise, recursively invert the left subtree and the right subtree, then assign th… |
| # Invert a binary tree by swapping left and right children at every node. # Returns the root of the inverted tree (or nil if the input is nil). def invert_binary_tree(root) return nil if root.nil? # Recursively invert the subtrees, then swap them root.left, root.right = in… |
| require "test/unit" class TreeNode attr_accessor :val, :left, :right def initialize(val = 0, left = nil, right = nil) @val = val @left = left @right = right end end class InvertBinaryTreeTest < Test::Unit::TestCase def test_empty_tree assert_nil(invert_b… |
| Given a binary tree where each node contains an integer value, write a Ruby method that returns the tree mirrored horizontally (i.e., inverted) by swapping every node's left and right children. The method should accept the root node (of type `TreeNode` with attributes `val`, `lef… |
| test-first order |
| 0fe7cf4f-357d-4bba-928f-1166d040a2cb | Given an array of chicken and tag IDs from a legacy join table, write a Ruby method that validates and normalizes the many-to-many relationship data. The input is an array of hashes, each with `:chicken_id` and `:tag_id` keys (integers). The method should return a new array with … | no fence | class ChickensTags < ActiveRecord::Base belongs_to :chicken belongs_to :tag end | Given an array of chicken and tag IDs from a legacy join table, write a Ruby method that validates and normalizes the many-to-many relationship data. The input is an array of hashes, each with `:chicken_id` and `:tag_id` keys (integers). The method should return a new array with … | The solution iterates through the input array, checking each hash for required keys `:chicken_id` and `:tag_id`. If a key is missing or the value is not an integer (using `Integer` type check), raise `ArgumentError` with a descriptive message. For valid entries, convert to a pair… | require "set" # Normalize chicken-tag join data by removing duplicate pairs and validating input. # @param records [Array<Hash>] array of hashes with :chicken_id and :tag_id keys # @return [Array<Array(Integer, Integer)>] unique [chicken_id, tag_id] pairs # @raise [ArgumentError… | require "test/unit" class NormalizeChickenTagsTest < Test::Unit::TestCase def test_removes_duplicates_preserving_order input = [ { chicken_id: 1, tag_id: 10 }, { chicken_id: 2, tag_id: 20 }, { chicken_id: 1, tag_id: 10 }, { chicken_id: 3, tag_id: 30… | Given an array of chicken and tag IDs from a legacy join table, write a Ruby method that validates and normalizes the many-to-many relationship data. The input is an array of hashes, each with `:chicken_id` and `:tag_id` keys (integers). The method should return a new array with … | standard order |
| 880908fd-b5d9-4c94-bc40-14834253d58c | Using the provided code snippet as a model, write a standalone Ruby method `simulate_route_matching` that takes a routing pattern string (containing literal segments, single-character wildcards `?`, and multi-segment wildcards `/`) and an input path string, and returns an array o… | markdown | require 'strscan' module ActionDispatch module Journey # :nodoc: module GTG # :nodoc: class MatchData # :nodoc: attr_reader :memos def initialize(memos) @memos = memos end end class Simulator # :nodoc: attr_read… | Using the provided code snippet as a model, write a standalone Ruby method `simulate_route_matching` that takes a routing pattern string (containing literal segments, single-character wildcards `?`, and multi-segment wildcards `/`) and an input path string, and returns an array o… | The core idea is to build a nondeterministic finite automaton from the pattern. Each character (or segment) in the pattern becomes a transition symbol. We define states as integers starting from 0 (initial state). For each symbol in the pattern (where a symbol is either a wildcar… | require 'strscan' # Simulate a route matcher using an NFA built from a pattern string. # Returns [1] if the path matches the pattern (reaches an accepting state), # otherwise returns []. # Pattern tokens: '/' (literal slash), '?' (any single character), # or a literal substring … | require 'test/unit' class SimulateRouteMatchingTest < Test::Unit::TestCase def test_basic_literal_match assert_equal([1], simulate_route_matching("users", "users")) end def test_literal_mismatch assert_equal([], simulate_route_matching("users", "posts")) end … | =begin Using the provided code snippet as a model, write a standalone Ruby method `simulate_route_matching` that takes a routing pattern string (containing literal segments, single-character wildcards `?`, and multi-segment wildcards `/`) and an input path string, and returns an … | solution-first order |
| 920e1fc0-e2f0-4773-b229-199705dd568b | Create a Ruby method called `transform_collection` that takes any enumerable collection (array, hash, range) and a block, and returns an array containing the result of applying the block to each element. For hashes, the block should receive both key and value (as separate block p… | no fence | require 'pry' system 'clear' # First time solving def map(collection) collection.each_with_object([]) { |element, result| result << yield(element) } end # Second time solving def map(array) result = [] array.each do |element| result << yield(element) end result en… | Create a Ruby method called `transform_collection` that takes any enumerable collection (array, hash, range) and a block, and returns an array containing the result of applying the block to each element. For hashes, the block should receive both key and value (as separate block p… | The core algorithm is straightforward: create an empty result array, iterate through each element in the collection, yield that element to the block, and append the block's return value to the result array. The key challenge is handling different collection types. For arrays and … | # Transform each element of an enumerable collection using a block. # Works with arrays, ranges, and hashes (yielding key & value to block). # Returns a new array of transformed values. Does not modify the original. def transform_collection(collection) result = [] collection.… | require "test/unit" class TransformCollectionTest < Test::Unit::TestCase def test_array_square assert_equal([1, 4, 9], transform_collection([1, 2, 3]) { |n| n * n }) end def test_empty_array assert_equal([], transform_collection([]) { |n| n + 1 }) end def tes… | =begin Create a Ruby method called `transform_collection` that takes any enumerable collection (array, hash, range) and a block, and returns an array containing the result of applying the block to each element. For hashes, the block should receive both key and value (as separate … | solution-first order |
| 51d492fc-5947-4474-ab36-7c015017038f | =begin Write a Ruby method that takes a DNSKEY record represented as a Hash with keys `:name`, `:flags`, `:protocol`, `:algorithm`, `:public_key`, and `:ttl`, along with a digest type (either an Integer or a String matching "SHA-1", "SHA-256", or "SHA-384"), and returns a Hash re… | code comment | require 'base64' require 'digest/sha2' module Dnsruby class RR # RFC4034, section 4 # The DS Resource Record refers to a DNSKEY RR and is used in the DNS # DNSKEY authentication process. A DS RR refers to a DNSKEY RR by # storing the key tag, algorithm number,… | Write a Ruby method that takes a DNSKEY record represented as a Hash with keys `:name`, `:flags`, `:protocol`, `:algorithm`, `:public_key`, and `:ttl`, along with a digest type (either an Integer or a String matching "SHA-1", "SHA-256", or "SHA-384"), and returns a Hash represent… | The solution requires implementing two RFC 4034 components: key tag computation and DS digest generation. For the key tag: if the public key length (after Base64 decoding) is less than 512 bytes, compute the key tag as the sum of all octets of the RDATA (flags as 16-bit big-endia… | require 'base64' require 'digest' # Compute the DS record for a given DNSKEY record. # key_hash must contain :name, :flags, :protocol, :algorithm, :public_key (Base64 string), :ttl # digest_type can be Integer (1,2,4) or String ("SHA-1", "SHA-256", "SHA-384") def compute_ds_reco… | require "test/unit" class DSRecordTest < Test::Unit::TestCase def test_sha256_ds key = { name: "example.com.", flags: 256, protocol: 3, algorithm: 8, public_key: "AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLA… | Write a Ruby method that takes a DNSKEY record represented as a Hash with keys `:name`, `:flags`, `:protocol`, `:algorithm`, `:public_key`, and `:ttl`, along with a digest type (either an Integer or a String matching "SHA-1", "SHA-256", or "SHA-384"), and returns a Hash represent… | standard order |
| d66d9e87-b99a-4d6e-9aa3-91a6ba4f39d4 | =begin Write a Ruby method that takes two positive integers, `start` and `finish`, and returns an array of all prime numbers in the inclusive range from `start` to `finish` whose last digit is 3. The method should handle the case where `start` is greater than or equal to `finish`… | code comment | require 'prime' x = ARGV[0].to_i y = ARGV[1].to_i if x < y (x..y).each do |n| if n % 10 == 3 && Prime.prime?(n) puts n end end else raise "First argument should be smaller than the second." end | Write a Ruby method that takes two positive integers, `start` and `finish`, and returns an array of all prime numbers in the inclusive range from `start` to `finish` whose last digit is 3. The method should handle the case where `start` is greater than or equal to `finish` by ret… | The solution iterates through the inclusive range from `start` to `finish`, checking two conditions for each number `n`: (1) the last digit must be 3 (i.e., `n % 10 == 3`), and (2) the number must be prime according to Ruby's `Prime.prime?`. We collect qualifying numbers into an … | require 'prime' # Returns an array of prime numbers from start to finish (inclusive) that end in digit 3. # If start is greater than finish, returns an empty array. # @param start [Integer] the beginning of the range (positive) # @param finish [Integer] the end of the range (pos… | require "test/unit" class PrimesEndingInThreeTest < Test::Unit::TestCase def test_normal_range assert_equal([3, 13, 23, 43], primes_ending_in_three(1, 50)) end def test_start_greater_than_finish assert_equal([], primes_ending_in_three(50, 1)) end def test_sin… | Write a Ruby method that takes two positive integers, `start` and `finish`, and returns an array of all prime numbers in the inclusive range from `start` to `finish` whose last digit is 3. The method should handle the case where `start` is greater than or equal to `finish` by ret… | standard order |
| f5ad90ad-1f23-4fc8-afcd-3e45e40ca3f7 | =begin Write a Ruby method that takes an integer count and returns the string "odd" if the number is odd, or "even" if the number is even. The method should handle edge cases such as zero (which is even), negative numbers (where -1 is odd, -2 is even), and very large integers tha… | code comment | module MoviesHelper # Checks if a number is odd: def oddness(count) count.odd? ? "odd" : "even" end end | Write a Ruby method that takes an integer count and returns the string "odd" if the number is odd, or "even" if the number is even. The method should handle edge cases such as zero (which is even), negative numbers (where -1 is odd, -2 is even), and very large integers that may e… | The solution approach is straightforward: determine if a number is odd using Ruby's built-in `odd?` method, which works on integers and returns a boolean. The primary algorithm involves checking the input's type and value. First, we need to verify the input is numeric: if it's a … | # Determines whether a given number is odd or even. # Works with integers, float values that represent integers, and handles edge cases. # Raises ArgumentError for non-numeric input or non-integer floats. # # @param value [Numeric] the number to check # @return [String] "odd" if … | require "test/unit" class OddnessCheckTest < Test::Unit::TestCase def test_odd_numbers assert_equal("odd", oddness_check(1)) assert_equal("odd", oddness_check(-1)) assert_equal("odd", oddness_check(101)) assert_equal("odd", oddness_check(-99)) end def test… | # Write a Ruby method that takes an integer count and returns the string "odd" if the number is odd, or "even" if the number is even. The method should handle edge cases such as zero (which is even), negative numbers (where -1 is odd, -2 is even), and very large integers that may… | test-first order |
| 8dd582ae-250f-4549-a713-7811786ceaf0 | Write a Ruby method `separate_comma` that takes a non-negative integer and returns a string representation of that integer with commas inserted every three digits from the right, following standard Western number grouping. The method should handle integers of any size, including … | no fence | require_relative "my_solution" #=> Make sure you change this to the name of your code file! Save that file # into this repo. def random_num(min, max) rand(max - min + 1) + min end describe "separate_comma" do it "returns no comma, when the integer is smaller than 1000" do… | Write a Ruby method `separate_comma` that takes a non-negative integer and returns a string representation of that integer with commas inserted every three digits from the right, following standard Western number grouping. The method should handle integers of any size, including … | The main algorithm is to convert the integer to a string and then insert commas from the right by iterating over the string in reverse, inserting a comma after every third digit. To do this without indexing pitfalls, the simplest approach is to convert the number to a string, the… | # Return the integer as a string with commas placed every three digits from the right. # The input must be a non-negative integer. def separate_comma(number) digits = number.to_s result = "" digits.chars.reverse.each_with_index do |char, index| result = char + result … | require "test/unit" class SeparateCommaTest < Test::Unit::TestCase def test_small_numbers_no_comma assert_equal "0", separate_comma(0) assert_equal "1", separate_comma(1) assert_equal "12", separate_comma(12) assert_equal "123", separate_comma(123) assert_e… | # Write a Ruby method `separate_comma` that takes a non-negative integer and returns a string representation of that integer with commas inserted every three digits from the right, following standard Western number grouping. The method should handle integers of any size, includin… | test-first order |
| 612e2135-54b8-4e5d-8928-5008ce6cc7cf | Create a Ruby method named `calculate_operation_result` that takes three arguments: two numbers (integers or floats) and a string representing an arithmetic operation (`"add"`, `"subtract"`, `"multiply"`, or `"divide"`). The method should perform the corresponding operation and r… | no fence | class Calculator def self.sum(number_one, number_two) number_one + number_two end end | Create a Ruby method named `calculate_operation_result` that takes three arguments: two numbers (integers or floats) and a string representing an arithmetic operation (`"add"`, `"subtract"`, `"multiply"`, or `"divide"`). The method should perform the corresponding operation and r… | The main algorithm is straightforward: take the two numeric inputs and apply the operation based on the string. For addition, subtraction, and multiplication, the result type follows Ruby's numeric coercion rules (integer + integer = integer, float involved = float). For division… | # Performs the specified arithmetic operation on two numbers. # # @param number_one [Numeric] the first operand # @param number_two [Numeric] the second operand # @param operation [String] one of "add", "subtract", "multiply", "divide" # @return [Numeric] the result of the operat… | require "test/unit" class CalculateOperationResultTest < Test::Unit::TestCase def test_add_integers assert_equal 5, calculate_operation_result(2, 3, "add") end def test_add_floats assert_in_delta 5.5, calculate_operation_result(2.5, 3.0, "add"), 0.0001 end de… | Create a Ruby method named `calculate_operation_result` that takes three arguments: two numbers (integers or floats) and a string representing an arithmetic operation (`"add"`, `"subtract"`, `"multiply"`, or `"divide"`). The method should perform the corresponding operation and r… | test-first order |
| 9fbfa4cb-8e4d-4e66-b89d-d14fc733ecc0 | =begin Write a Ruby method that performs hash-based search in an array and returns the first index (0-based) where the target value appears. The method will receive a hash map already constructed where keys are array elements and values are their indices, plus the target value to… | code comment | =begin File: hashing_search.rb Created Time: 2024-04-09 Author: Blue Bean (<EMAIL>) =end require_relative '../utils/list_node' ### 哈希查找(数组) ### def hashing_search_array(hmap, target) # 哈希表的 key: 目标元素,value: 索引 # 若哈希表中无此 key ,返回 -1 hmap[target] || -1 end ### 哈希查找(链表) ### … | Write a Ruby method that performs hash-based search in an array and returns the first index (0-based) where the target value appears. The method will receive a hash map already constructed where keys are array elements and values are their indices, plus the target value to find. … | The solution leverages Ruby's hash lookup which has O(1) average time complexity for key access. The main algorithm is straightforward: given the hash map `hmap` and the `target`, we return `hmap[target]` if the key exists, otherwise return -1. Ruby's `Hash#[]` returns `nil` for … | # Returns the first index of target in the array represented by the hash map. # The hash map keys are element values, values are their first occurrence indices. # Returns -1 if target is not present. def hash_search_array(hmap, target) hmap[target] || -1 end | require "test/unit" class HashSearchArrayTest < Test::Unit::TestCase def test_finds_first_index hmap = {1=>0, 5=>1, 3=>2, 2=>3, 4=>4} assert_equal(2, hash_search_array(hmap, 3)) end def test_finds_index_zero hmap = {10=>0, 20=>1} assert_equal(0, hash_searc… | Write a Ruby method that performs hash-based search in an array and returns the first index (0-based) where the target value appears. The method will receive a hash map already constructed where keys are array elements and values are their indices, plus the target value to find. … | commented standard order |
| 80f8a1e0-b277-4566-a60d-93447f9f9f45 | =begin Write a Ruby method that measures and reports the performance of hash operations (insertion, lookup, and deletion) over a range of integer keys. The method should accept a positive integer `n` representing the maximum key (1 through `n`), populate a hash with `key => key` … | code comment | start = Time.now map = Hash.new for i in (1..1000000) map[i] = i end sum = 0 for i in (1..1000000) sum = sum + map[i] end puts sum for i in (1..1000000) map.delete(i) end puts "elapsed: " + (Time.now - start).to_s | Write a Ruby method that measures and reports the performance of hash operations (insertion, lookup, and deletion) over a range of integer keys. The method should accept a positive integer `n` representing the maximum key (1 through `n`), populate a hash with `key => key` mapping… | The solution involves three main phases: insertion, summation, and deletion, all timed from before the first operation to after the last. First, record the start time with `Time.now`. Then, iterate from 1 to `n` (inclusive), inserting `i => i` into a hash. Next, compute the sum b… | # Measure hash insertion, lookup, and deletion over keys 1..n. # Returns a string with the computed sum and elapsed seconds. def hash_operation_report(n) start_time = Time.now map = {} (1..n).each { |i| map[i] = i } sum = 0 (1..n).each { |i| sum += map[i] } (1..… | require "test/unit" class HashOperationReportTest < Test::Unit::TestCase def test_small_range result = hash_operation_report(5) assert_match(/^sum: 15, elapsed: \d+\.\d+$/, result) end def test_larger_range_sum result = hash_operation_report(100) assert_ma… | # Write a Ruby method that measures and reports the performance of hash operations (insertion, lookup, and deletion) over a range of integer keys. The method should accept a positive integer `n` representing the maximum key (1 through `n`), populate a hash with `key => key` mappi… | standard order |
| c2d01197-8e00-4d4e-a468-0e5952fa3347 | Write a Ruby method called `sort_strings_by_last_character` that takes an array of strings (which may include uppercase, lowercase, digits, punctuation, and empty strings) and returns a new array with the strings sorted in ascending order based only on their last character's ASCI… | markdown | def insertion_sort(array) array.each_with_index do |item, index| index.downto(1) do |i| # puts "#{item} at #{index}, #{i}th iteration" if item < array[i - 1] array.insert(i - 1, item) array.delete_at(i + 1) end end end end def insert… | Write a Ruby method called `sort_strings_by_last_character` that takes an array of strings (which may include uppercase, lowercase, digits, punctuation, and empty strings) and returns a new array with the strings sorted in ascending order based only on their last character's ASCI… | The solution must sort an array of strings by the ASCII value of their last character. For each string, we first extract the last character: if the string is empty, we treat its key as 0; otherwise, we take `str[-1].ord` which gives the integer ordinal. Since Ruby's built-in `sor… | # Sort an array of strings by the ASCII value of their last character. # Empty strings are treated as having a last character value of 0. # The sort is stable: strings with equal last characters keep original order. # Returns a new array; does not modify the input. def sort_strin… | require "test/unit" class SortStringsByLastCharacterTest < Test::Unit::TestCase def test_basic_sorting input = ["banana", "Apple", "grape!", "12", ""] expected = ["", "grape!", "12", "Apple", "banana"] assert_equal expected, sort_strings_by_last_character(input) … | =begin Write a Ruby method called `sort_strings_by_last_character` that takes an array of strings (which may include uppercase, lowercase, digits, punctuation, and empty strings) and returns a new array with the strings sorted in ascending order based only on their last character… | solution-first order |
| 2d2705d9-155f-47c2-8b35-55ea1e9c2468 | Create a Ruby class called `CharacterAttributeSpan` that maintains an array of integer attribute flags parallel to the characters in a string. The class must support three core operations: initialization with a specified length, setting a range of attribute bits via a bitwise OR,… | markdown | ## # An array of attributes which parallels the characters in a string. class RDoc::Markup::AttrSpan ## # Creates a new AttrSpan for +length+ characters def initialize(length) @attrs = Array.new(length, 0) end ## # Toggles +bits+ from +start+ to +length+ def… | Create a Ruby class called `CharacterAttributeSpan` that maintains an array of integer attribute flags parallel to the characters in a string. The class must support three core operations: initialization with a specified length, setting a range of attribute bits via a bitwise OR,… | The solution is straightforward but requires careful handling of index bounds and Ruby's array semantics. The constructor creates an array of the given length, initialized to zero for every position. The `set_attrs` method should iterate from the starting index up to (but not inc… | class CharacterAttributeSpan # Creates a new span for +length+ characters. def initialize(length) @attrs = Array.new(length, 0) end # Toggles +bits+ from +start+ to +length+ (exclusive), safely clamping to valid range. def set_attrs(start, length, bits) low = [… | require "test/unit" class CharacterAttributeSpanTest < Test::Unit::TestCase def test_initialization span = CharacterAttributeSpan.new(5) assert_equal([0, 0, 0, 0, 0], span.instance_variable_get(:@attrs)) assert_nil(span[-1]) assert_nil(span[5]) end def tes… | Create a Ruby class called `CharacterAttributeSpan` that maintains an array of integer attribute flags parallel to the characters in a string. The class must support three core operations: initialization with a specified length, setting a range of attribute bits via a bitwise OR,… | test-first order |
| 25b21fec-f08c-4250-b775-45475724a67a | Write a Ruby method `factorial` that computes the factorial of a non-negative integer using recursion. The method should accept one argument, `number`, which is a non-negative integer (0 or greater). It must return the factorial value, defined as the product of all positive integ… | no fence | ### 問題021:階乗 ### # 非負の階乗値を返す関数を定義してください。 # 引数「number」は正の整数です。 ### 例 ### # factorial(5) => 「120」 ### 条件 ### # ・階乗値は再帰的な処理で実装してください。 # (factorial関数の中でfactorial関数を呼び出す) ### 再帰処理とは? ### # ・自分自身を用いる処理のこと。 def factorial(number) end ### 実装確認 ### # 下記のコメントアウトを解除すると確認できます。 # VSCod… | Write a Ruby method `factorial` that computes the factorial of a non-negative integer using recursion. The method should accept one argument, `number`, which is a non-negative integer (0 or greater). It must return the factorial value, defined as the product of all positive integ… | The factorial of a non-negative integer `n` is defined as: - `0! = 1` - `n! = n * (n - 1)!` for `n > 0` The recursive approach follows directly from this definition. The base case is when `number <= 1`, in which case we return `1` (this correctly handles both `0!` and `1!`). For… | # Compute the factorial of a non-negative integer using recursion. # # @param number [Integer] a non-negative integer # @return [Integer] the factorial of number def factorial(number) return 1 if number <= 1 number * factorial(number - 1) end | require "test/unit" class FactorialTest < Test::Unit::TestCase def test_factorial_zero assert_equal(1, factorial(0)) end def test_factorial_one assert_equal(1, factorial(1)) end def test_factorial_two assert_equal(2, factorial(2)) end def test_factor… | Write a Ruby method `factorial` that computes the factorial of a non-negative integer using recursion. The method should accept one argument, `number`, which is a non-negative integer (0 or greater). It must return the factorial value, defined as the product of all positive integ… | standard order |
| 94e9d646-d1e0-49c3-bed1-3bead5b51e59 | =begin Write a Ruby method called `leap_year?` that takes a single integer `year` as an argument and returns `true` if the year is a leap year, otherwise `false`. Use the Gregorian calendar rules: a year is a leap year if it is divisible by 4, except for years divisible by 100, u… | code comment | # Leap Years # I worked on this challenge [by myself, with: Chris Miklius ]. # Your Solution Below def leap_year?(year) if year%400 == 0 p true elsif year%100 == 0 p false elsif year%4 == 0 p true else p false end end | Write a Ruby method called `leap_year?` that takes a single integer `year` as an argument and returns `true` if the year is a leap year, otherwise `false`. Use the Gregorian calendar rules: a year is a leap year if it is divisible by 4, except for years divisible by 100, unless t… | The solution follows the standard leap year algorithm with priority given to the divisibility rules. The main logic is: 1. If the year is divisible by 400, it is a leap year (e.g., 1600, 2000). 2. Else if the year is divisible by 100 but not by 400, it is NOT a leap year (e.g., 1… | # Check if a given year is a leap year according to the Gregorian calendar. # Returns true if leap year, false otherwise. def leap_year?(year) if year % 400 == 0 true elsif year % 100 == 0 false elsif year % 4 == 0 true else false end end | require "test/unit" class LeapYearTest < Test::Unit::TestCase def test_leap_year # Standard leap years assert_equal(true, leap_year?(2000)) assert_equal(true, leap_year?(2004)) assert_equal(true, leap_year?(2016)) assert_equal(false, leap_year?(1900)) a… | =begin Write a Ruby method called `leap_year?` that takes a single integer `year` as an argument and returns `true` if the year is a leap year, otherwise `false`. Use the Gregorian calendar rules: a year is a leap year if it is divisible by 4, except for years divisible by 100, u… | solution-first order |
| b445f898-35af-44fc-8633-eae13d6bc085 | =begin Write a Ruby method named `print_odd_letters` that takes two arguments: a starting letter and an ending letter (both lowercase English characters), and returns a string containing every second character from the starting letter up to and including the ending letter if the … | code comment | # ('a'..'z').each{|e| print e} # puts ('a'..'z').step(2){|e| print e} puts | Write a Ruby method named `print_odd_letters` that takes two arguments: a starting letter and an ending letter (both lowercase English characters), and returns a string containing every second character from the starting letter up to and including the ending letter if the range l… | The core task is to iterate over a character range and collect every second element. Ruby’s `Range#step(2)` provides exactly this functionality, but we must be careful: `('a'..'z').step(2)` yields letters at indices 0,2,4,... relative to the range, which corresponds to every seco… | # Returns a string containing every second letter from start to finish inclusive, using lowercase English letters. # Raises ArgumentError if start or finish are not single lowercase letters, or if start > finish. def print_odd_letters(start_letter, finish_letter) unless start_l… | require "test/unit" class PrintOddLettersTest < Test::Unit::TestCase def test_full_alphabet assert_equal("acegikmoqsuwy", print_odd_letters('a', 'z')) end def test_single_letter assert_equal("a", print_odd_letters('a', 'a')) end def test_two_letters asser… | # Write a Ruby method named `print_odd_letters` that takes two arguments: a starting letter and an ending letter (both lowercase English characters), and returns a string containing every second character from the starting letter up to and including the ending letter if the range… | commented standard order |