From 585e904e4610c52b85e69f9e0b995a9b9a854861 Mon Sep 17 00:00:00 2001 From: Shugo Maeda Date: Fri, 10 Jun 2022 15:06:08 +0900 Subject: [PATCH 1/7] Add questions for version 3 and Japanese translation --- .ruby-version | 1 + README.md | 4 +- check_gold.rb | 80 ++ check_silver.rb | 72 ++ gold.md | 390 ++++++---- gold_answers.md | 71 +- gold_answers_ja.md | 437 +++++++++++ gold_ja.md | 1741 ++++++++++++++++++++++++++++++++++++++++++ silver.md | 348 +++++---- silver_answers.md | 87 ++- silver_answers_ja.md | 477 ++++++++++++ silver_ja.md | 977 ++++++++++++++++++++++++ 12 files changed, 4284 insertions(+), 401 deletions(-) create mode 100644 .ruby-version create mode 100644 check_gold.rb create mode 100644 check_silver.rb create mode 100644 gold_answers_ja.md create mode 100644 gold_ja.md create mode 100644 silver_answers_ja.md create mode 100644 silver_ja.md diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..fd2a018 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.1.0 diff --git a/README.md b/README.md index 67f7874..6da783c 100644 --- a/README.md +++ b/README.md @@ -2,5 +2,5 @@ Sample questions for [Ruby Association Certified Ruby Programmer Examination](https://www.ruby.or.jp/en/certification/examination/) -* [Sample Questions for Silver](silver.md) -* [Sample Questions for Gold](gold.md) +* [Sample Questions for Silver](silver.md) ([Japanese](silver_ja.md)) +* [Sample Questions for Gold](gold.md) ([Japanese](gold_ja.md)) diff --git a/check_gold.rb b/check_gold.rb new file mode 100644 index 0000000..af5e2ce --- /dev/null +++ b/check_gold.rb @@ -0,0 +1,80 @@ +require "open3" +require "rbconfig" + +$questions = File.read("gold.md").split(/^-------------.*\n/) +$answers = File.read("gold_answers.md").split(/^-------------.*\n/) + +$ruby = File.join(RbConfig::CONFIG["bindir"], RbConfig::CONFIG["ruby_install_name"]) + +def check(n) + question = $questions[n - 1] + answer = $answers[n - 1] + case question + when /Assume that the following code must have the stated execution result|Which code produces the following execution result\?/ + s = question.slice(/^```\n(.*?)^```\n/m, 1) + code, output = s.split(/\n?\[Execution Result\]\n+/) + options = question.scan(/^\*[A-Z]:\* `(.*)`/).flatten(1) + if options.empty? + options = question.scan(/^\*[A-Z]:\*.*\n((?:(?!\*[A-Z]:\*).*\n)*)/).flatten(1).map { |i| + i.slice(/^```\n(.*)^```\n/m, 1) || i + } + end + xs = answer.slice(/^\*\*A\d+:.*/).scan(/\(([A-Z])\)/).flatten(1).map { |i| + i.ord - ?A.ord + } + if question.match?(/Which of the following options CANNOT be inserted into/) + xs = (0 .. options.size - 1).to_a - xs + end + ys = options.each_with_index.filter_map { |option, i| + c = code.strip.empty? ? option : c = code.gsub(/__\(1\)__/, option) + o, = Open3.capture2e($ruby, stdin_data: c) + if $VERBOSE + p [i, o, output] + end + o == output ? i : nil + } + result = xs == ys ? "OK" : "NG" + puts "Q#{n}: #{result}" + when /Which option corresponds to the execution result\?/ + code = question.slice(/^```\n(.*?)^```\n/m, 1) + options = question.scan(/^(?:- )?\*[A-Z]:\* (.+)/).flatten(1).map { |i| + i.slice(/`(.*)`/, 1) || i + } + if options.empty? + options = question.scan(/^\*[A-Z]:\*.*\n((?:(?!\*[A-Z]:\*).*\n)*)/).flatten(1).map { |i| + i.slice(/^```\n(.*)^```\n/m, 1) || i + } + end + output, = Open3.capture2e($ruby, stdin_data: code) + if $VERBOSE + p [output, options] + end + xs = answer.slice(/^\*\*A\d+:.*/).scan(/\(([A-Z])\)/).flatten(1).map { |i| + i.ord - ?A.ord + } + ys = options.each_with_index.filter_map { |option, i| + case option + when /no output/i + output.strip.empty? + when /a syntax error/i + output.match?(/syntax error/) + when /an exception is raised|an error occurs/i + output.match?(/\(.*Error\)/) + else + output.strip == option.strip + end ? i : nil + } + result = xs == ys ? "OK" : "NG" + puts "Q#{n}: #{result}" + else + puts "Q#{n}: ?" + end +end + +if ARGV[0] + check(ARGV[0].to_i) +else + (1..50).each do |i| + check(i) + end +end diff --git a/check_silver.rb b/check_silver.rb new file mode 100644 index 0000000..1cdd9b4 --- /dev/null +++ b/check_silver.rb @@ -0,0 +1,72 @@ +require "open3" +require "rbconfig" + +$questions = File.read("silver.md").split(/^-------------.*\n/) +$answers = File.read("silver_answers.md").split(/^-------------.*\n/) + +$ruby = File.join(RbConfig::CONFIG["bindir"], RbConfig::CONFIG["ruby_install_name"]) + +def check(n) + question = $questions[n - 1] + answer = $answers[n - 1] + case question + when /Which of the following can be inserted into/ + s = question.slice(/^```\n(.*?)^```\n/m, 1) + code, output = s.split(/\n\[Output\]\n/) + options = question.scan(/^- \([a-z]\) `(.*)`/).flatten(1) + xs = answer.slice(/^\*\*A\d+:.*/).scan(/\(([a-z])\)/).flatten(1).map { |i| + i.ord - ?a.ord + } + ys = options.each_with_index.filter_map { |option, i| + c = code.gsub(/__\(1\)__/, option) + o, = Open3.capture2e($ruby, stdin_data: c) + if $VERBOSE + p [i, o, output] + end + o == output ? i : nil + } + result = xs == ys ? "OK" : "NG" + puts "Q#{n}: #{result}" + when /Given the following:/ + code = question.slice(/^```\n(.*?)^```\n/m, 1) + options = question.scan(/^- \([a-z]\) (.*)/).flatten(1).map { |i| + i.slice(/`(.*)`/, 1) || i + } + if options.empty? + options = question.scan(/^\*\([a-z]\).*\n((?:(?!\*\([a-z]\)).*\n)*)/).flatten(1).map { |i| + i.slice(/^```\n(.*)^```\n/m, 1) || i + } + end + output, = Open3.capture2e($ruby, stdin_data: code) + if $VERBOSE + p output + end + xs = answer.slice(/^\*\*A\d+:.*/).scan(/\(([a-z])\)/).flatten(1).map { |i| + i.ord - ?a.ord + } + ys = options.each_with_index.filter_map { |option, i| + case option + when /no output/i + output.strip.empty? + when /a syntax error/i + output.match?(/syntax error/) + when /an exception is raised|an error occurs/i + output.match?(/\(.*Error\)/) + else + output.strip == option.strip + end ? i : nil + } + result = xs == ys ? "OK" : "NG" + puts "Q#{n}: #{result}" + else + puts "Q#{n}: ?" + end +end + +if ARGV[0] + check(ARGV[0].to_i) +else + (1..50).each do |i| + check(i) + end +end diff --git a/gold.md b/gold.md index d808241..cb45dff 100644 --- a/gold.md +++ b/gold.md @@ -2,41 +2,66 @@ [Answers](gold_answers.md) -**Q1. Assume that the following code must have the stated execution result.** +**Q1. Assume that the following code must have the stated execution result:** ``` -__(1)__ -x.each_line { |line| puts line } +class Stack + def initialize + @contents = [] + end + + __(1)__ +end + +stack = Stack.new +stack.push("foo") +stack.push("bar") +p stack.pop [Execution Result] -apple -banana +"bar" ``` -**Which option can be inserted into `__(1)__`? (Choose one.)** +**Which option can be inserted into `__(1)__`? (Choose two.)** *A:* ``` -require "stringbuffer" -x = StringBuffer.new("apple\nbanana\n") +[:push, :pop].each do |name| + define_method(name) do |*args| + @contents.send(name, *args) + end +end ``` *B:* ``` -require "stringio" -x = StringIO.new("apple\nbanana\n") +for name in [:push, :pop] + define_method(name) do |*args| + @contents.send(name, *args) + end +end ``` *C:* ``` -require "strio" -x = StrIO.new("apple\nbanana\n") +[:push, :pop].each do |name| + instance_eval(<<-EOF) + def #{name}(*args) + @contents.send(:#{name}, *args) + end + EOF +end ``` *D:* ``` -require "mockio" -x = MockIO.new("apple\nbanana\n") +[:push, :pop].each do |name| + class_eval(<<-EOF) + def #{name}(*args) + @contents.send(:#{name}, *args) + end + EOF +end ``` ----------------------------------------------------------------- @@ -113,42 +138,37 @@ p ("aaaaaa".."zzzzzz").lazy.select { |e| e.end_with?("f") }.__(1)__ ----------------------------------------------------------------- -**Q5: Given the following code:** +**Q5. Assume that the following code must have the stated execution result:** ``` -arr = [] - -f = Fiber.new { - arr << "A" - Fiber.yield "B" - Fiber.yield "C" -} +def round(n, __(1)__) + n.round(__(1)__) +end -arr << "X" -arr << f.resume -arr << "Y" +p round(2.5, half: :even) -p arr +[Execution Result] +2 ``` -**Which option corresponds to the execution result? (Choose one.)** +**Which option can be inserted into `__(1)__`? (Choose two.)** -*A:* `["A", "B", "C", "X", "Y"]` +*A:* `*` -*B:* `["X", "A", "B", "Y"]` +*B:* `**` -*C:* `["X", "A", "B", "C", "Y"]` +*C:* `..` -*D:* `["X", "A", nil, "Y"]` +*D:* `...` ----------------------------------------------------------------- -**Q6. Assume that the following code must have the stated execution result:** +**Q6. Given the following code:** ``` class A def foo - __1__ + self.bar end private @@ -156,23 +176,32 @@ class A def bar "baz" end -end -p A.new.foo + def self.bar + "quux" + end +end -[Execution Result] -"baz" +puts A.new.foo ``` -**Which option can be inserted into `__(1)__`? (Choose one.)** +**Which option corresponds to the execution result? (Choose one.)** -*A:* `bar` +*A:* +``` +baz +``` -*B:* `self.bar` +*B:* +``` +quux +``` -*C:* `A.new.bar` +*C:* +A syntax error occurs -*D:* None of the above. +*D:* +An exception is raised ----------------------------------------------------------------- @@ -424,50 +453,67 @@ HELLO **Q14. Assume that the following code must have the stated execution result:** ``` -old_data = [1,2,3] -old_data.freeze - -new_data = old_data.__(1)__ - -new_data << 4 +__(1)__ + x + y +end -p new_data +p add(1, 2) [Execution Result] - -[1,2,3,4] +3 ``` **Which option can be inserted into `__(1)__`? (Choose one.)** -*A:* `dup` +*A:* `add = ->(x, y) do` -*B:* `clone` +*B:* `add = lambda do |x, y|` -*C:* `copy` +*C:* `add = Proc.new do |x, y|` -*D:* None of the above. There is no way to make this code work. +*D:* `define_method(:add) do |x, y|` ----------------------------------------------------------------- **Q15. Given the following code:** ``` -original = [[1,2],[3,4]] +def reader_method(s) + <<~EOF + def #{s} + @#{s} + end + EOF +end -copy = original.dup +print reader_method("foo") +``` -original[0][0] = 42 +**Which option corresponds to the execution result? (Choose one.)** -p copy +*A:* +``` + def foo + @foo + end ``` -**Which option corresponds to the execution result? (Choose one.)** +*B:* +``` + def foo + @foo + end +``` + +*C:* +``` +def foo + @foo +end +``` -- *A:* `[[1,2],[3,4]]` -- *B:* `[[42,2],[3,4]]` -- *C:* `[[42],[3,4]]` -- *D:* A runtime error occurs. +*D:* +A syntax error occurs. ----------------------------------------------------------------- @@ -488,7 +534,7 @@ copy.hello Hi! ``` -**Which option can be inserted `__(1)__` ? (Choose one.)** +**Which option can be inserted into `__(1)__`? (Choose one.)** *A:* `Marshal.load(Marshal.dump(obj))` @@ -513,7 +559,7 @@ class ShoppingList end def __(1)__ - @items.map { |e| "- #{e} " }.join("\n") + @items.map { |e| "- #{e}" }.join("\n") end end @@ -556,7 +602,7 @@ class ShoppingList end def __(1)__ - "ShoppingList (##{object_id})\n @items: #{@items.inspect}" + "ShoppingList:\n @items: #{@items.inspect}" end end @@ -569,7 +615,7 @@ list.add_item("Eggs") p list [Execution Result] -ShoppingList (#70338683731980) +ShoppingList: @items: ["Milk", "Bread", "Eggs"] ``` @@ -585,35 +631,57 @@ ShoppingList (#70338683731980) ----------------------------------------------------------------- -**Q19. Which of the following statements is true? (Choose one.)** +**Q19. Assume that the following code must have the stated execution result.** + +``` +p __(1)__.flat_map {|z| + (1..z).flat_map {|x| + (x..z).select {|y| + x**2 + y**2 == z**2 + }.map {|y| + [x, y, z] + } + } +}.take(3).to_a + +[Execution Result] +[[3, 4, 5], [6, 8, 10], [5, 12, 13]] +``` + +**Which option can be inserted into `__(1)__`? (Choose one.)** -*A:* `Kernel#puts` calls `to_str` on its arguments to produce a string representation. +*A:* `(1..-1).delay` -*B:* `Kernel#p` calls `to_str` on its arguments to produce a string representation. +*B:* `(1..).delay` -*C:* A default implementation of `to_str` is provided by Ruby's `Object` class +*C:* `(1..-1).lazy` -*D:* The `to_str` method is meant to be implemented only by objects that can behave similarly to `String` instances. +*D:* `(1..).lazy` ----------------------------------------------------------------- -**Q20. Given the following code:** +**Q20. Assume that the following code must have the stated execution result.** ``` -a, b, c = ["apple", "banana", "carrot", "daikon"] +ary = ["foo", "bar", nil, "baz"] -p c +p ary.__(1)__ { |i| + i&.upcase +} + +[Execution Result] +["FOO", "BAR", "BAZ"] ``` -**Which option corresponds to the execution result?** +**Which option can be inserted into `__(1)__`? (Choose one.)** -*A:* `["apple", "banana", "carrot", "daikon"]` +*A:* `map` -*B:* `"carrot"` +*B:* `filter_map` -*C:* `["carrot"]` +*C:* `collect` -*D:* `["carrot", "daikon"]` +*D:* `collect_compact` ----------------------------------------------------------------- @@ -678,28 +746,24 @@ fx(["apple", "banana", "carrot"]) ----------------------------------------------------------------- -**Q23. Given the following code:** +**Q23. Assume that the following code must have the stated execution result.** ``` -def add(x,y) - x + y -end - -__(1)__ +p ["foo", "bar", "baz"].map { __(1)__.upcase } [Execution Result] -5 +["FOO", "BAR", "BAZ"] ``` -**Which options can be inserted into `__(1)__`? (Choose two.)** +**Which option can be inserted into `__(1)__`? (Choose one.)** -*A:* `p add(3,2)` +*A:* `_1` -*B:* `p add(*[3,2])` +*B:* `$1` -*C:* `p add([3,2])` +*C:* `$_` -*D:* `p add(**[[3,2]])` +*D:* `it` ----------------------------------------------------------------- @@ -714,7 +778,7 @@ end fx(b: "banana") ``` -**Which option corresponds to the execution result:** +**Which option corresponds to the execution result?** *A:* ``` @@ -728,9 +792,11 @@ nil banana ``` -*C:* A syntax error occurs +*C:* +A syntax error occurs -*D:* An exception is raised +*D:* +An exception is raised ----------------------------------------------------------------- @@ -820,7 +886,7 @@ end *C:* `nil` -*D:* A syntax error is raised +*D:* A syntax error occurs ----------------------------------------------------------------- @@ -853,7 +919,6 @@ puts "done!" x y done! - ``` **Which option can be inserted into `__(1)__`? (Choose one.)** @@ -904,7 +969,7 @@ abc ``` begin - raise __(1)__ + __(1)__ rescue puts "OK" end @@ -1083,7 +1148,7 @@ end def greeting "hello" ensure - puts "Ensured called!" + puts "Ensure called!" "hi" end @@ -1307,14 +1372,11 @@ Hello World! **Which of the following options can be inserted into `__(1)__`? (Choose one.)** -*A:* -`Mixin.greet` +*A:* `Mixin.greet` -*B:* -`SomeClass.new.greet` +*B:* `SomeClass.new.greet` -*C:* -`SomeClass.greet` +*C:* `SomeClass.greet` *D:* `Mixin.new.greet` @@ -1341,14 +1403,11 @@ Hello World! **Which of the following options can be inserted into `__(1)__`? (Choose one.)** -*A:* -`Mixin.greet` +*A:* `Mixin.greet` -*B:* -`SomeClass.new.greet` +*B:* `SomeClass.new.greet` -*C:* -`SomeClass.greet` +*C:* `SomeClass.greet` *D:* `Mixin.new.greet` @@ -1413,38 +1472,27 @@ end **Q44. Assume that the following code must have the stated execution result:** ``` -class Upcaser - def initialize(value) - @value = value - end - - def +(other) - self.class.new(@value + other.value) - end - - def to_s - @value.upcase - end - - attr_reader :value - __(1)__ +h = [1, 2, 3] +case h +__(1)__ [x, y] + p [:two, x, y] +__(1)__ [x, y, z] + p [:three, x, y, z] end -puts Upcaser.new("Hello") + Upcaser.new("World") - [Execution Result] -HELLOWORLD +[:three, 1, 2, 3] ``` -**Which of the following options can be inserted into `__(1)__`? (Choose two.)** +**Which of the following options can be inserted into `__(1)__`? (Choose one.)** -*A:* `private :value` +*A:* `when` -*B:* `public :value` +*B:* `in` -*C:* `protected :value` +*C:* `if` -*D:* `static :value` +*D:* `=>` ----------------------------------------------------------------- @@ -1603,69 +1651,91 @@ puts(date >> 12) **Q48. Assume that the following code must have the stated execution result:** ``` -require "date" +require "time" -d = Date.new(2000, 2, 18) -puts d __(1)__ 3 +t = Time.__(1)__("00000024021993", "%S%M%H%d%m%Y") +puts t.iso8601 [Execution Result] -2000-02-21 +1993-02-24T00:00:00+09:00 ``` **Which option can be inserted into `__(1)__`? (Choose one.)** -*A:* `+` +*A:* `format` -*B:* `>>` +*B:* `parse` -*C:* `<<` +*C:* `strftime` -*D:* `*` +*D:* `strptime` ----------------------------------------------------------------- -**Q49. Assume that the following code reads the contents of the example.com homepage over HTTP:** +**Q49. Assume that the following code must have the stated execution result:** ``` -__(1)__ +require "singleton" + +class Foo + __(1)__ +end + +x = Foo.instance +y = Foo.instance +p x.equal?(y) -puts open("http://example.com").read +[Execution Result] +true ``` -**What option can be inserted into `__(1)__`? (Choose one.)** +**Which option can be inserted into `__(1)__`? (Choose one.)** -*A:* `require "uri"` +*A:* `include Singleton` -*B:* `require "net/http"` +*B:* `extend Singleton` -*C:* `require "open3"` +*C:* `using Singleton` -*D:* `require "open-uri"` +*D:* `singletonize` ----------------------------------------------------------------- **Q50. Assume that the following code must have the stated execution result:** ``` -if __(1)__ == "Henry" - puts "Hi Henry!!!" -else - puts "Hello, stranger." +require 'forwardable' + +class List + extend Forwardable + + def initialize + @contents = [] + end + + __(1)__ :@contents, :push + __(1)__ :@contents, :[] end +list = List.new +list.push("a") +list.push("b") +list.push("c") +p list[1] + [Execution Result] -Hi Henry!!! +"b" ``` **Which option can be inserted into `__(1)__`? (Choose one.)** -*A:* `ENV['EMPLOYEE_NAME']` +*A:* `forward` -*B:* `$env['EMPLOYEE_NAME']` +*B:* `def_forwarder` -*C:* `ENV[:EMPLOYEE_NAME]` +*C:* `def_delegator` -*D:* `$env[:EMPLOYEE_NAME]` +*D:* `define` ----------------------------------------------------------------- diff --git a/gold_answers.md b/gold_answers.md index 2db6d93..5fd0e09 100644 --- a/gold_answers.md +++ b/gold_answers.md @@ -1,6 +1,8 @@ -**A1:** (B) +**A1:** (A), (D) -The `StringIO` object (from the standard library) provides an IO-like object that operates on strings rather than file/network/stdio streams. This object can be useful for testing code that relies on I/O operations. +[Module#define_method](https://docs.ruby-lang.org/en/3.1/Module.html#method-i-define_method) defines an instance method in the receiver. However, the variable `name` is shared by `Stack#push` and `Stack#pop` in (B), so both methods call `@contents.send(:pop, *args)`. + +`def` defines a singleton method in [BasicObject#instance_eval](https://docs.ruby-lang.org/en/3.1/BasicObject.html#method-i-instance_eval), while `def` defines an instance method in [Module#class_eval](https://docs.ruby-lang.org/en/3.1/Module.html#method-i-class_eval). ----------------------------------------------------------------- @@ -34,21 +36,15 @@ Note that the `force()` method on `Enumerator::Lazy` is just an alias for `Enume ----------------------------------------------------------------- -**A5:** (B) - -A `Fiber` is used to implement coroutine-like functionality which allows for partially completing a computation before returning control back the the caller, and then resuming later to compute the next result. - -The block provided when initializing a `Fiber` is not executed immediately, but instead gets run whenever `Fiber#resume` is called. Execution will continue until `Fiber.yield` is called or until the end of the block is reached, and then the result will be returned. +**A5:** (D) -If the fiber yields, then the next call to `Fiber#resume` would continue execution immediately after that instruction in the block. +`...` forwards rest arguments including keyword arguments and the block. ----------------------------------------------------------------- **A6:** (A) -Private methods can only be invoked in functional style from within a class definition. - -Calling `self.some_method()` attempts to invoke a method via an object's external API, therefore it will raise an exception if `some_method()` is a private method. +Private methods cannot be called with an explicit receiver, except when the receiver is `self`. ----------------------------------------------------------------- @@ -116,17 +112,17 @@ The `->(...) { }` (lambda literal) syntax is a shorthand notation equivalent to ----------------------------------------------------------------- -**A14:** (A) +**A14:** (D) -The frozen status of an object is preserved by `clone`, whereas `dup` will create an unfrozen shallow copy of an object that can be modified. +`define_method` at toplevel defines a method in `Object`. ------------------------------------------------------------------ +(A), (B), and (C) creates an `Proc` object, and assigns it to a local variable `add`, but `add(1, 2)` doesn't call the `Proc` object. -**A15:** (B) +----------------------------------------------------------------- -Both `Object#dup` and `Object#clone` produce shallow copies. In the case of an `Array`, this means that the array itself is copied, but the objects within the array are not. So in this specific example `original[0]` and `copy[0]` both still reference the same object. +**A15:** (C) -One convention that can be used for creating deep copies in Ruby is to serialize and then deserialize an object, using the `Marshal` core class, e.g. `copy = Marshal.load(Marshal.dump(original))`. +`<<~EOF` is called a squiggly heredoc, and it strips leading whitespace. ----------------------------------------------------------------- @@ -158,13 +154,15 @@ The `Kernel#p` method calls `inspect` on its arguments in order to produce strin **A19:** (D) -The `to_str` method is rarely implemented in practice, because it is only useful for situations in which you have an object that closely maps to Ruby's `String` concept, but is not a `String` itself. So while this method might be implemented by certain low-level data structures, it is not meant to be used for similar purposes to what `to_s` and `inspect` are used for. +`x..` represents a semi-infinite range. + +[Enumerable#lazy](https://docs.ruby-lang.org/en/3.1/Enumerable.html#method-i-lazy) returns an Enumerator::Lazy, which redefines most Enumerable methods to postpone enumeration and enumerate values only on an as-needed basis. ----------------------------------------------------------------- **A20: (B)** -When an array is used on the right hand side of a parallel assignment statement, it is expanded as much as needed to map rvalues to the lvalues listed on the left hand side. This means that the number of variables on the left hand side does not need to be equal to the the length of the array. +[Enumerable#filter_map](https://docs.ruby-lang.org/en/3.1/Enumerable.html#method-i-filter_map) returns an array containing truthy elements returned by the block. ----------------------------------------------------------------- @@ -180,10 +178,9 @@ The splat operator (`*`) when used with a method parameter makes it so that all ----------------------------------------------------------------- -**A23:** (A) and (B) - -When the splat operator (`*`) is called on an array in a method call, the array is expanded and treated as an arguments list to be passed to the method. +**A23:** (A) +`_1`, `_2`, `_3`... are implicitly defined block parameters called **numbered parameters**. ----------------------------------------------------------------- @@ -207,7 +204,7 @@ Because classes are objects in Ruby, it is possible to define class instance var All objects in Ruby also have a *singleton class* associated with them, even class objects. -In this example, there is an instance variable named `@message`on the `Speaker` class as well as on the singleton class of `Speaker`. These are two seperate variables. +In this example, there is an instance variable named `@message` on the `Speaker` class as well as on the singleton class of `Speaker`. These are two seperate variables. The singleton method `Speaker.speak` is evaluated in the context of the `Speaker` class, and so `@message` refers to the instance variable defined within the `Speaker` class definition, and not the instance variable defined within the singleton class of `Speaker`. @@ -243,7 +240,7 @@ ArgumentError < StandardError < Exception ScriptError < Exception ``` -If `rescue` is called without a specific error class, it will catch `StandardError` and its descendents by default. Most exceptions in core Ruby are descendents of `StandardError`, but there are some that are not usually meant to be rescued which exist in other class hierarchies which descend directly from the `Exception` base clase. +If `rescue` is called without a specific error class, it will catch `StandardError` and its descendents by default. Most exceptions in core Ruby are descendents of `StandardError`, but there are some that are not usually meant to be rescued which exist in other class hierarchies which descend directly from the `Exception` base class. ----------------------------------------------------------------- @@ -332,7 +329,7 @@ obj.greet ----------------------------------------------------------------- -**A42:** B +**A42:** (B) The `include` method mixes a module into a class so that its methods become available as instance methods. @@ -344,12 +341,11 @@ A `protected` method can only be called from within an instance of the same clas ----------------------------------------------------------------- -**A44:** (B) and (C) +**A44:** (B) -Note that: +[Pattern matching](https://docs.ruby-lang.org/en/3.1/syntax/pattern_matching_rdoc.html) is a feature allowing deep matching of structured values. -- Private methods are not directly callable from another object, even if it is an instance of the same class. -- There is no `static` keyword in Ruby. +For pattern matching, `in` is used instead of `when` in the `case` expression. ----------------------------------------------------------------- @@ -413,22 +409,25 @@ puts(Date.new(2016,12,31) << 2) #=> 2016-10-31 ----------------------------------------------------------------- -**A48:** (A) +**A48:** (D) -The `+` operator is used to produce a new `Date` object that is *n days* later. -There is also a `-` operator which produces dates that are *n days* earlier. +[Time.strptime](https://docs.ruby-lang.org/en/3.1/Time.html#method-c-strptime) parses the given string with the given template, and creates a Time object. + +[Time.parse](https://docs.ruby-lang.org/en/3.1/Time.html#method-c-parse) parses the given string using a heuristic, and doesn't take a template. ----------------------------------------------------------------- -**A49:** (D) +**A49:** (A) + +The `Singleton` module implements [the Singleton pattern](http://w3sdesign.com/?gr=c05&ugr=proble). -The `OpenURI` standard library extends the functionality of `Kernel#open` to allow treating HTTP-based resources as if they were a file. It is a wrapper around the low-level `Net::HTTP` standard library. +`include Singleton` adds the class method `instance`, which returns the only instance of the class. ----------------------------------------------------------------- -**A50:** (A) +**A50:** (C) -Environment variables are accessed via the `ENV` constant, which refers to a Hash-like object that represents both the variable names and their values as strings. +The `Forwardable` module provides delegation of specified methods to a designated object, using [Forwardable.def_delegator](https://docs.ruby-lang.org/en/3.1/Forwardable.html#method-i-def_delegator) ----------------------------------------------------------------- diff --git a/gold_answers_ja.md b/gold_answers_ja.md new file mode 100644 index 0000000..35815ad --- /dev/null +++ b/gold_answers_ja.md @@ -0,0 +1,437 @@ +**A1:** (A), (D) + +[Module#define_method](https://docs.ruby-lang.org/ja/3.1/class/Module.html#I_DEFINE_METHOD)はレシーバにインスタンスメソッドを定義します。ただし、(B)では変数`name`が`Stack#push`と`Stack#pop`で共有されるため、両方とも`@contents.send(:pop, *args)`を呼びます。 + +[BasicObject#instance_eval](https://docs.ruby-lang.org/ja/3.1/class/BasicObject.html#I_INSTANCE_EVAL)では`def`は特異メソッドを定義しますが、[Module#class_eval](https://docs.ruby-lang.org/ja/3.1/class/Module.html#I_CLASS_EVAL)ではインスタンスメソッドを定義します。 + +----------------------------------------------------------------- + +**A2:** (A) + +- スーパークラスが明示的に指定されていないクラスは自動的に`Object`を継承します。`Object`は`Kernel`モジュールをmixinし、`BasicObject`を継承しています。 + +- `include`によってmixinされたモジュールは、継承チェーン上で当該クラスとそのスーパークラスの間に現れます。 + +- `prepend`によってmixinされたモジュールは、継承チェーン上で当該クラスより前に現れます。 + +`prepend`が必要なのは、クラスの定義をモジュールのmixinで上書きしたい時だけです。それ以外の場合は`include`で十分で、すでにインクルードされている他のモジュールの機能を上書きすることもできます。 + +----------------------------------------------------------------- + +**A3:** (A) + +数値リテラルの末尾の`r`は`Rational`オブジェクトを生成することを意味します。 +同じ結果を他の方法(例: `1 / 3.to_r`または`Rational(1, 3)`)によって得ることもできます。 + +----------------------------------------------------------------- + +**A4:** (A), (C) + +`take`メソッドは`Enumerator::Lazy`によって定義され、列挙が何らかの方法によって強制されるまで実行が遅延されます(このメソッドの返り値は`Enumerator::Lazy`オブジェクトです)。 + +`Enumerator::Lazy`は`Enumerator`を継承し、`Enumerable`をインクルードしています。 + +`Enumerator::Lazy`によってオーバーライドされていない`Enumerable`のメソッドの呼び出しは、列挙を強制します。`first(3)`が`.force`の呼び出しを必要としないのはこのためで、操作がただちに実行され`Enumerator::Lazy`ではなく`Array`が返されます。 + +`Enumerator::Lazy`の`force`は`Enumerable#to_a`のただの別名であることに注意してください。 + +----------------------------------------------------------------- + +**A5:** (D) + +`...`は、キーワード引数やブロックを含め、残りの引数を転送します。 + +----------------------------------------------------------------- + +**A6:** (A) + +プライベートメソッドの呼び出し時に明示的にレシーバを指定することはできません。ただし、`self`をレシーバとして指定することはできます。 + +----------------------------------------------------------------- + +**A7:** (B), (C) + +`class << ...`構文はオブジェクトの特異クラスを定義するために使用され、特定のオブジェクトにメソッドを定義することができます。 + +Rubyではクラスもオブジェクトであるため、次のようにクラスにメソッドを追加することができます。 + +``` +class << Greeter + def hello + # ... + end +end +``` + +しかし、問題文のようにクラス定義の中で`class << self`を使用する方が一般的です。 + +--------------------------------------------------------------- + +**A8:** (A), (C) + +メソッド定義で指定されているかどうかに関らず、Rubyのすべてのメソッドはブロックを受け付けます。 + +予約語`yield`はブロックを暗黙的に呼ぶために使用されます。 +`&block`はブロックを`Proc`オブジェクトに変換するために使用され、`call()`によってブロックを呼び出したり、他のメソッドに渡したりすることができます。 + +----------------------------------------------------------------- + +**A9:** (B), (C) + +- `yield`によってブロックに引数を渡して呼ぶ場合は、`yield(x)`のように関数風に記述します。 +- `Proc`オブジェプトによってブロックを呼ぶ場合は、引数を`call()`メソッドに渡します。 + +----------------------------------------------------------------- + +**A10:** (B) + +クラス変数は一つのクラス内で共有されるだけでなく、継承階層の下位にも共有されます。しがたって`A`に定義された`@@x`は、子クラスの`B`と`C`にも共有され、同じ変数が参照されます。 + +クラス変数はRubyのもっとも複雑な機能の一つで、このガイドでは基本的な動作についてのみ説明します。 + +----------------------------------------------------------------- + +**A11:** (D) + +`Proc`オブジェクトはブロックをカプセル化し、後で`Proc#call`によって呼び出すことを可能にします。`Proc`オブジェクトはクロージャを形成し、`Proc`オブジェクトが生成された時のローカル変数をブロックに結び付けます。 + +----------------------------------------------------------------- + +**A12:** (A), (C) + +`Proc.new`と`lambda`はいずれも`Proc`オブジェクトを生成しますが、その挙動はまったく同じというわけではありません。 + +- `lambda`によって生成された`Proc`は引数のチェックが厳密なのに対し、通常の`Proc`は使用されない引数を無視します。 + +- `lambda`内での`return`はその`lambda`自体から返りますが、通常の`Proc`内での`return`はブロックが記述されたメソッドから返ります。 + +----------------------------------------------------------------- + +**A13:** (A) + +`->(...) { }`(ラムダリテラル)構文は`lambda { |...| }`と同等の省略記法です。 + +----------------------------------------------------------------- + +**A14:** (D) + +トップレベルの`define_method`は`Object`にメソッドを定義します。 + +(A), (B), (C)では`Proc`を生成してローカル変数`add`に代入していますが、`add(1, 2)`は`Proc`を呼び出しません。 + +----------------------------------------------------------------- + +**A15:** (C) + +`<<~EOF`はsquiggly heredocと呼ばれ、先頭の空白が除去されます。 + +----------------------------------------------------------------- + +**A16:** (C) + +補足説明です。 + +- `Object#dup`はオブジェクトの特異メソッドをコピーしません。 +- `Marshal.dump`は特異メソッドをもつオブジェクトをシリアライズできません。 +- `Object#copy`というメソッドはありません。 + +----------------------------------------------------------------- + +**A17:** (A) + +多くのRubyのメソッド(`Kernel#puts`を含む)はオブジェクトを文字列に変換する際に`to_s`を呼び出します。`Object#to_s`のデフォルトの実装は、以下のように単純で一般的な出力を行います。 + +`#` + +`to_s`をオーバーライドすると、問題文のようによりよい文字列表現を提供することができます。 + +----------------------------------------------------------------- + +**A18:** (C) + +`Kernel#p`は引数に対して`inspect`を呼び出してデバッグ用途の文字列に変換します。`Object#inspect`のデフォルトの機能は基本的な情報を提供しますが、特定のクラスやオブジェクトでオーバーライドすることでカスタマイズできます。 + +----------------------------------------------------------------- + +**A19:** (D) + +`x..`は半無限区間を表現します。 + +[Enumerable#lazy](https://docs.ruby-lang.org/ja/3.1/class/Enumerable.html#I_LAZY)はEnumerator::Lazyを返します。Enumerator::LazyはEnumerableの多くのメソッドを再定義しており、列挙を必要になった時まで遅延させます。 + +----------------------------------------------------------------- + +**A20: (B)** + +[Enumerable#filter_map](https://docs.ruby-lang.org/ja/3.1/class/Enumerable.html#I_FILTER_MAP)はブロックが返した値のうち、真の値だけを配列として返します。 + +----------------------------------------------------------------- + +**A21: (D)** + +splat演算子(`*`)はすべての残りの右辺値を配列として一つの変数に代入します。 + +----------------------------------------------------------------- + +**A22:** (B) + +splat演算子(`*`)は、メソッドの引数で使用された場合、残りのすべての引数を配列として一つの引数で参照できるようにします。回答の*(B)*では、`fx(*args)`は0個以上の引数を取り、すべての引数を配列`args`で保持します。`fx(["apple", "banana", "carrot"])`が呼び出されると単一の引数である配列が引数のリストを表す配列の中に配置され、`args`は`[["apple","banana","carrot"]]`を参照します。 + +----------------------------------------------------------------- + +**A23:** (A) + +`_1`, `_2`, `_3`...は暗黙に定義されるブロックパラメータで、ナンバードパラメータと呼ばれます。 + +----------------------------------------------------------------- + +**A24:** (D) + +必要なキーワード引数が指定されなかった場合、`ArgumentError`が発生します。 + +----------------------------------------------------------------- + +**A25:** (B), (C), (D) + +キーワード引数を使用する際、`**`演算子は明示的に指定されなかったキーワード引数をHashで受け取るために使用できます。 + +`**`演算子は、メソッド呼び出しの際にHashをキーワード引数に変換するために使用することもできます。 + +----------------------------------------------------------------- + +**A26:** (A), (C) + +Rubyではクラスはオブジェクトなので、クラスのインスタンス変数を定義することができます。 + +すべてのオブジェクトは、クラスも含め、特異クラスをもちます。 + +この例では、`Speaker`クラスとその特異クラスに`@message`というインスタンス変数が定義されています。これらは別々の変数です。 + +特異メソッド`Speaker.speak`は`Speaker`クラスのコンテキストで評価され、`@message`は特異クラスのインスタンス変数ではなく`Speaker`クラスのインスタンス変数を参照します。 + +----------------------------------------------------------------- + +**A27:** (B) + +この例では、`class << Speaker`は`Speaker`の特異クラス定義を再オープンし、そこでの`@message`は特異クラスに直接定義されたインスタンス変数を参照します。 + +----------------------------------------------------------------- + +**A28:** (C) + +`catch`ブロックでは、`throw`が実行されるまでコードが実行されます。`catch`に対応するシンボルが`throw`に渡されると、Rubyはブロックの実行を終了し、ブロックの次の処理から実行を継続します。 + +`catch`が`throw`に対応しない場合は、外側の`catch`が内側から順番に探され、トップレベルに到達すると例外が発生します。 + +----------------------------------------------------------------- + +**A29:** (C) + +2引数の`throw`が使用された場合、2番目の引数が対応する`catch`の呼び出しの値として返されます。 + +----------------------------------------------------------------- + +**A30:** (A), (C) + +問題文のクラスの継承チェーンはそれぞれ以下のとおりです。 + +``` +ArgumentError < StandardError < Exception + +ScriptError < Exception +``` + +`rescue`に特定の例外クラスが指定されなかった場合、デフォルトで`StandardError`とそのサブクラスが捕捉されます。ほとんどの組み込み例外クラスは`StandardError`のサブクラスですが、通常捕捉されることを想定していないいくつかの例外クラスは`Exception`を直接継承しています。 + +----------------------------------------------------------------- + +**A31:** (C) + +`rescue`に特定の例外クラスが指定されなかった場合、`StandardError`とそのサブクラスが捕捉されます。したがって、`Exception`を直接継承したクラスは捕捉されません。 + +一つの`begin/end`ブロックでは、複数の`rescue`節がマッチした場合も、最初にマッチした`rescue`節だけが実行されます。 + +----------------------------------------------------------------- + +**A32:** (D) + +`rescue Exception`と`rescue AnError`はいずれも発生した例外にマッチしますが、この例では`rescue Exception`が先に指定されているため実行され、残りの`rescue`節は無視されます。 + +----------------------------------------------------------------- + +**A33:** (D) + +`rescue`節で`=>`が使用された場合、発生した例外が変数に代入されます。 + +----------------------------------------------------------------- + +**A34:** (A) + +`rescue`節で`raise`が引数なしで呼び出された場合、捕捉された例外が再度`raise`されます。 + +例外が捕捉されていないコンテキストで`raise`が引数なしで呼び出された場合、デフォルトで`RuntimeError`が`raise`されます。 + +----------------------------------------------------------------- + +**A35:** (C) + +メソッド(または`begin/end`ブロック)の`ensure`節は、例外が発生してもしなくても、常に実行されます。ただし、`ensure`節の値は返り値としては使用されず、`ensure`節が実行される直前の評価結果が返り値として使用されます。 + +----------------------------------------------------------------- + +**A36: (B)** + +予約語`self`は現在のオブジェクトを表します。クラスメソッドでは、`self`は現在のクラスを表す`Class`インスタンスを参照します。インスタンスメソッドでは、`self`は現在のクラスの特定のインスタンスを参照します。 + +----------------------------------------------------------------- + +**A37:** (B) + +In class methods, `self` refers to an instance of the `Class` object. +In instance methods, `self` refers to whatever the currently instantiated object is. +クラスメソッドでは、`self`は`Class`インスタンスを参照します。 +インスタンスメソッドでは、`self`は現在インスタンス化されているオブジェクトを参照します。 + +----------------------------------------------------------------- + +**A38:** (D) + +モジュールのmixinやクラスの継承が使用された複雑な継承チェーンにおいても、`self`は常に現在のコンテキストにおけるオブジェクトを参照します。 + +この例では、`this_object`は`Mixin`で定義されていますが、`Indentity`クラスにインクルードされており、`self`は`Identity`の特定のオブジェクトを参照します。 + +----------------------------------------------------------------- + +**A39:** (B) + +`Class`は`Module`のサブクラスですが、クラスオブジェクトはmixinとしては使用できません(つまり、`include`、`extend`、`prepend`に`Class`オブジェクトを渡すことはできません)。 + +Rubyにおける`Module`と`Class`の継承関係は実装の詳細であり、機能と用途に重複はあるものの、どちらか一方がもう一方の純粋なサブタイプであるというわけではありません。 + +----------------------------------------------------------------- + +**A40:** (A) + +この例では`greet`メソッドは`Mixin`モジュール自体の特異メソッドとして定義され、他のクラスにmixinすることはできません。 + +(モジュールの特異メソッドと他のクラスへmixinするためのメソッドを同時に定義する方法については、`moudle_function`という機能や`extend self`という慣習についての情報を参照してください。) + +----------------------------------------------------------------- + +**A41:** (C) + +`extend`メソッドはモジュールを一つのオブジェクトにmixinするために使用されます。クラス定義で使用された場合は、`extend`はクラス自身にmixinするため、mixinされたメソッドはクラスメソッドして使用できます。 + +しかし、`extend`はクラス以外のオブジェクトにも使用できます。 + +``` +obj = Object.new +obj.extend(Mixin) +obj.greet +``` + +----------------------------------------------------------------- + +**A42:** (B) + +`include`メソッドはモジュールをクラスにmixinし、mixinされたメソッドはインスタンスメソッドとして使用できます。 + +----------------------------------------------------------------- + +**A43:** (B) + +`protected`メソッドは同じクラスかそのサブクラスのインスタンスからのみ呼び出すことができます。 + +----------------------------------------------------------------- + +**A44:** (B) + +パターンマッチは構造化された値に対して深いマッチングを行うための機能です。 + +パターンマッチでは、`case`式で`when`の代りに`in`を使用します。 + +----------------------------------------------------------------- + +**A45:** (B) + +`Enumerable`はmixinされるオブジェクトが要素を一つずつブロックに渡す`each`メソッドを実装していることを想定しています。`Enumerable`のさまざまなリスト操作は`each`にもとづいて実装されています。 + +`Enumerable`をより深く理解するため、`each`を使って他の機能がどのように実装されているか考えてみましょう。例えば、`each`がすでに定義されていれば、`select`は次のように定義できます。 + +``` +def select(&b) + matched = [] + + each { |e| matched << e if b.call(e) } + + matched +end +``` + +この汎用的なパターンはmixinでは一般的です。mixinの機能は、mixinされるオブジェクトのとてもシンプルな機能にもとづいていて、mixinの機能を使用するためにはちょっとしたグルーコードを書くだけで済みます。 + +----------------------------------------------------------------- + +**A46:** (B) + +`Comparable`モジュールはこの例で使用されているすべての比較メソッド(`<`, `<=`, `==`, `>=`, `>`)を提供しています。 + +Each of these methods rely on the presence of a `<=>` operator which returns a negative number, zero, or a positive number depending on the sort order of two values. Ruby's core `Numeric` classes all implement this functionality, and so the following example with integers should help clarify: +これらのメソッドは、2つの要素のソート順序に応じて負の数、0、正の数のいずれかを返す`<=>`演算子に依存しています。Rubyのすべての組み込み数値クラスは、次の整数の例のように、この機能を実装しています。 + +``` +3 <=> 8 # -1 +8 <=> 8 # 0 +8 <=> 3 # 1 +``` + +これを使用して、`Comparable#<`は次のように実装することができます。 + +``` +def <(other) + (self <=> other) < 0 +end +``` + +`Enumerable`同様に`Comparable`は、モジュールがいかにクラスに小さな機能だけ実装させて、mixinによってモジュールのすべての機能を提供するかを示すよい例です。 + +----------------------------------------------------------------- + +**A47:** (C) + +`<<`は現在の日付のn月前を表す`Date`オブジェクトを返します。 + +`>>`は現在の日付のn月後を表す`Date`オブジェクトを返します。 + +同じ日がその月に存在しない場合(例: 31日まである月と30までの月、うるう年とそれ以外の年などのケース)、`<<`と`>>`はその月の最後の有効な日付を返します。 + +``` +puts(Date.new(2016,2,29) << 12) #=> 2015-02-28 +puts(Date.new(2016,12,31) << 1) #=> 2016-11-30 +puts(Date.new(2016,12,31) << 2) #=> 2016-10-31 +``` + +----------------------------------------------------------------- + +**A48:** (D) + +[Time.strptime](https://docs.ruby-lang.org/ja/3.1/class/Time.html#C_STRPTIME)は文字列を与えられたテンプレートによって解析し、`Time`オブジェクトを返します。 + +[Time.parse](https://docs.ruby-lang.org/ja/3.1/class/Time.html#C_PARSE)はヒューリスティックを使用して文字列を解析し、テンプレートは受け取りません。 + +----------------------------------------------------------------- + +**A49:** (A) + +`Singleton`モジュールはSingletonパターンを実装します。 + +`include Singleton`はクラスの唯一のインスタンスを返す`instance`メソッドを追加します。 + +----------------------------------------------------------------- + +**A50:** (C) + +`Forwardable`モジュールは、[Forwardable.def_delegator](https://docs.ruby-lang.org/ja/3.1/class/Forwardable.html#I_DEF_DELEGATOR)を使用して、指定されたメソッドを特定のオブジェクトに委譲します。 + +----------------------------------------------------------------- + diff --git a/gold_ja.md b/gold_ja.md new file mode 100644 index 0000000..6364923 --- /dev/null +++ b/gold_ja.md @@ -0,0 +1,1741 @@ +# Ruby技術者認定試験Gold模擬問題 + +[回答](gold_answers_ja.md) + +**Q1. 以下の実行結果を出力するコードがあります。** + +``` +class Stack + def initialize + @contents = [] + end + + __(1)__ +end + +stack = Stack.new +stack.push("foo") +stack.push("bar") +p stack.pop + +[実行結果] +"bar" +``` + +**__(1)__に入る適切な記述を選択してください。(2つ選択)** + +*A:* +``` +[:push, :pop].each do |name| + define_method(name) do |*args| + @contents.send(name, *args) + end +end +``` + +*B:* +``` +for name in [:push, :pop] + define_method(name) do |*args| + @contents.send(name, *args) + end +end +``` + +*C:* +``` +[:push, :pop].each do |name| + instance_eval(<<-EOF) + def #{name}(*args) + @contents.send(:#{name}, *args) + end + EOF +end +``` + +*D:* +``` +[:push, :pop].each do |name| + class_eval(<<-EOF) + def #{name}(*args) + @contents.send(:#{name}, *args) + end + EOF +end +``` + +----------------------------------------------------------------- + +**Q2. 以下のコードがあります。** + +``` +module I +end + +module P +end + +class C + include I + prepend P +end + +p C.ancestors +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* `[P, C, I, Object, Kernel, BasicObject]` + +*B:* `[C, P, I, Object, Kernel, BasicObject]` + +*C:* `[C, I, Object, Kernel, BasicObject, P]` + +*D:* `[P, I, C, Object, Kernel, BasicObject]` + +----------------------------------------------------------------- + +**Q3. 以下の実行結果を出力するコードがあります。** + +``` +x = __(1)__ +p x + 1 + +[実行結果] +(4/3) +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `1 / 3r` + +*B:* `1 / 3R` + +*C:* `1 / %r(3)` + +*D:* `1 / 3` + +----------------------------------------------------------------- + +**Q4. 以下の実行結果を出力するコードがあります。** + +``` +p ("aaaaaa".."zzzzzz").lazy.select { |e| e.end_with?("f") }.__(1)__ + +[実行結果] +["aaaaaf", "aaaabf", "aaaacf"] +``` + +**__(1)__に入る適切な記述を選択してください。(複数選択)** + +*A:* `first(3)` + +*B:* `take(3)` + +*C:* `take(3).force` + +*D:* `first(3).force` + +----------------------------------------------------------------- + +**Q5. 以下の実行結果を出力するコードがあります。** + +``` +def round(n, __(1)__) + n.round(__(1)__) +end + +p round(2.5, half: :even) + +[実行結果] +2 +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `*` + +*B:* `**` + +*C:* `..` + +*D:* `...` + +----------------------------------------------------------------- + +**Q6. 以下のコードがあります。** + +``` +class A + def foo + self.bar + end + + private + + def bar + "baz" + end + + def self.bar + "quux" + end +end + +puts A.new.foo +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* +``` +baz +``` + +*B:* +``` +quux +``` + +*C:* +文法エラーが発生する + +*D:* +例外が発生する + +----------------------------------------------------------------- + +**Q7. 以下の実行結果を出力するコードがあります。** + +``` +class Greeter + class << self + def hello + puts "Hello there!" + end + end +end + +__(1)__ + +[実行結果] +Hello there! +``` + +**__(1)__に入る適切な記述を選択してください。(2つ選択)** + +*A:* `Greeter.new.hello` + +*B:* `Greeter.hello` + +*C:* `Greeter.new.class.hello` + +*D:* `Greeter.class.new.hello` + +--------------------------------------------------------------- + +**Q8: 以下の実行結果を出力するコードがあります。** + +``` +__(1)__ + +p multiply_by(4) { 2 + 3 } + +[実行結果] +20 +``` + +**__(1)__に入る適切な記述を選択してください。(2つ選択)** + +*A:* + +``` +def multiply_by(n, &block) + n * block.call +end +``` + +*B:* + +``` +def multiply_by(n, &block) + n * block +end +``` + +*C:* + +``` +def multiply_by(n) + n * yield +end +``` + +*D:* + +``` +def multiply_by(n) + n * yield.call +end +``` + +----------------------------------------------------------------- + +**Q9: 以下の実行結果を出力するコードがあります。** + +``` +__(1)__ + +p sum { |e| e << 1 << 5 << 7 } + +[実行結果] +13 +``` + +**__(1)__に入る適切な記述を選択してください。(2つ選択)** + +*A:* + +``` +def sum(&block) + array = [] + + block(array) + + array.reduce(:+) +end +``` + +*B:* +``` +def sum(&block) + array = [] + + block.call(array) + + array.reduce(:+) +end +``` + +*C:* +``` +def sum + array = [] + + yield(array) + + array.reduce(:+) +end +``` + +*D:* +``` +def sum + array = [] + + yield.call(array) + + array.reduce(:+) +end +``` + +----------------------------------------------------------------- + +**Q10. 以下のコードがあります。** + +``` +class A + @@x = 1 +end + +class B < A + def self.x + @@x + end +end + +class C < A + def self.inc + @@x += 1 + end +end + +C.inc +p B.x +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- *A:* `1` + +- *B:* `2` + +- *C:* `3` + +- *D:* 例外が発生する + +----------------------------------------------------------------- + +**Q11. 以下の実行結果を出力するコードがあります。** + +``` +words = ["apple", "banana", "cabbage"] +pop = Proc.new { words.pop } +3.times{ puts __(1)__ } + +[実行結果] +cabbage +banana +apple +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `pop.load` + +*B:* `pop.send` + +*C:* `pop.run` + +*D:* `pop.call` + +*E:* `pop.eval` + +----------------------------------------------------------------- + +**Q12. 以下の実行結果を出力するコードがあります。** + +``` +words = ["apple", "banana", "cabbage"] +pop = __(1)__{ words.pop } +3.times{ puts pop.call } + +[実行結果] +cabbage +banana +apple +``` + +**__(1)__に入る適切な記述を選択してください。(2つ選択)** + +*A:* `Proc.new` + +*B:* `Block.new` + +*C:* `lambda` + +*D:* `Lambda.new` + +----------------------------------------------------------------- + +**Q13. 以下の実行結果を出力するコードがあります。** + +``` +add = __(1)__ +puts add.call("hello") + +[実行結果] +HELLO +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `->(e) { e.upcase }` + +*B:* `\(e) -> { e.upcase }` + +*C:* `-> { (e) e.upcase }` + +*D:* `-> { |e| e.upcase }` + +----------------------------------------------------------------- + +**Q14. 以下の実行結果を出力するコードがあります。** + +``` +__(1)__ + x + y +end + +p add(1, 2) + +[実行結果] +3 +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `add = ->(x, y) do` + +*B:* `add = lambda do |x, y|` + +*C:* `add = Proc.new do |x, y|` + +*D:* `define_method(:add) do |x, y|` + +----------------------------------------------------------------- + +**Q15. 以下のコードがあります。** + +``` +def reader_method(s) + <<~EOF + def #{s} + @#{s} + end + EOF +end + +print reader_method("foo") +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* +``` + def foo + @foo + end +``` + +*B:* +``` + def foo + @foo + end +``` + +*C:* +``` +def foo + @foo +end +``` + +*D:* +文法エラーが発生する + +----------------------------------------------------------------- + +**Q16. 以下の実行結果を出力するコードがあります。** + +``` +obj = Object.new + +def obj.hello + puts "Hi!" +end + +copy = __(1)__ + +copy.hello + +[実行結果] +Hi! +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `Marshal.load(Marshal.dump(obj))` + +*B:* `obj.dup` + +*C:* `obj.clone` + +*D:* `obj.copy` + +----------------------------------------------------------------- + +**Q17. 以下の実行結果を出力するコードがあります。** + +``` +class ShoppingList + def initialize + @items = [] + end + + def add_item(item) + @items << item + end + + def __(1)__ + @items.map { |e| "- #{e}" }.join("\n") + end +end + +list = ShoppingList.new + +list.add_item("Milk") +list.add_item("Bread") +list.add_item("Eggs") + +puts list + +[実行結果] +- Milk +- Bread +- Eggs +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `to_s` + +*B:* `to_str` + +*C:* `inspect` + +*D:* `puts` + +----------------------------------------------------------------- + +**Q18. 以下の実行結果を出力するコードがあります。** + +``` +class ShoppingList + def initialize + @items = [] + end + + def add_item(item) + @items << item + end + + def __(1)__ + "ShoppingList:\n @items: #{@items.inspect}" + end +end + +list = ShoppingList.new + +list.add_item("Milk") +list.add_item("Bread") +list.add_item("Eggs") + +p list + +[実行結果] +ShoppingList: + @items: ["Milk", "Bread", "Eggs"] +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `to_s` + +*B:* `to_str` + +*C:* `inspect` + +*D:* `p` + +----------------------------------------------------------------- + +**Q19. 以下の実行結果を出力するコードがあります。** + +``` +p __(1)__.flat_map {|z| + (1..z).flat_map {|x| + (x..z).select {|y| + x**2 + y**2 == z**2 + }.map {|y| + [x, y, z] + } + } +}.take(3).to_a + +[実行結果] +[[3, 4, 5], [6, 8, 10], [5, 12, 13]] +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `(1..-1).delay` + +*B:* `(1..).delay` + +*C:* `(1..-1).lazy` + +*D:* `(1..).lazy` + +----------------------------------------------------------------- + +**Q20. 以下の実行結果を出力するコードがあります。** + +``` +ary = ["foo", "bar", nil, "baz"] + +p ary.__(1)__ { |i| + i&.upcase +} + +[実行結果] +["FOO", "BAR", "BAZ"] +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `map` + +*B:* `filter_map` + +*C:* `collect` + +*D:* `collect_compact` + +----------------------------------------------------------------- + +**Q21. 以下のコードがあります。** + +``` +a, b, *c = ["apple", "banana", "carrot", "daikon"] + +p c +``` + +**実行結果として正しいものを選択してください。** + +*A:* `["apple", "banana", "carrot", "daikon"]` + +*B:* `"carrot"` + +*C:* `["carrot"]` + +*D:* `["carrot", "daikon"]` + +----------------------------------------------------------------- + +**Q22: 以下の実行結果を出力するコードを選択してください。(1つ選択)** + +``` +[実行結果] +[["apple", "banana", "carrot"]] +``` + +*A:* +``` +def fx(*args) + p(args) +end +fx(*["apple", "banana", "carrot"]) +``` + +*B:* +``` +def fx(*args) + p(args) +end +fx(["apple", "banana", "carrot"]) +``` + +*C:* +``` +def fx(*args) + p(args) +end +fx("apple", "banana", "carrot") +``` + +*D:* +``` +def fx(*args) + p(*args) +end +fx(["apple", "banana", "carrot"]) +``` + +----------------------------------------------------------------- + +**Q23. 以下の実行結果を出力するコードがあります。** + +``` +p ["foo", "bar", "baz"].map { __(1)__.upcase } + +[実行結果] +["FOO", "BAR", "BAZ"] +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `_1` + +*B:* `$1` + +*C:* `$_` + +*D:* `it` + +----------------------------------------------------------------- + +**Q24. 以下のコードがあります。** + +``` +def fx(a:, b: "apple") + p a + p b +end + +fx(b: "banana") +``` + +**実行結果として正しいものを選択してください。** + +*A:* +``` +nil +apple +``` + +*B:* +``` +nil +banana +``` + +*C:* +文法エラーが発生する + +*D:* +例外が発生する + +----------------------------------------------------------------- + +**Q25. 以下の実行結果を出力するコードがあります。** + +``` +def add(x:, y:, **params) + z = x + y + + params[:round] ? z.round : z +end + +__(1)__ + +[実行結果] +7 +``` + +**__(1)__に入る適切な記述を選択してください。(3つ選択)** + +*A:* `p add(x: 2.75, y: 5.25, round: true)` + +*B:* `p add(x: 3.75, y: 3, round: true)` + +*C:* `options = {:round => true}; p add(x: 3.75, y: 3, **options)` + +*D:* `p add(x: 3, y: 4)` + +*E:* `p add(x: 7)` + +----------------------------------------------------------------- + +**Q26: 以下の実行結果を出力するコードがあります。** + +``` +class Speaker + @message = "Hello!" + + class << self + @message = "Howdy!" + + def speak + @message + end + end +end + +__(1)__ + +[実行結果] +Hello! +``` + +**__(1)__に入る適切な記述を選択してください。(2つ選択)** + +*A:* `puts Speaker.speak` + +*B:* `puts Speaker.singleton_class.speak` + +*C:* `puts Speaker.instance_variable_get(:@message)` + +*D:* `puts Speaker.singleton_class.instance_variable_get(:@message)` + +----------------------------------------------------------------- + +**Q27. 以下のコードがあります。** + +``` +class Speaker + @message = "Hello!" + + class << self + @message = "Howdy!" + end +end + +class << Speaker + p @message +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* `"Hello!"` + +*B:* `"Howdy!"` + +*C:* `nil` + +*D:* 文法エラーが発生する + +----------------------------------------------------------------- + +**Q28. 以下の実行結果を出力するコードがあります。** + +``` +def x + puts "x" +end + +def y + puts "y" + throw :done +end + +def z + puts "z" +end + + +__(1)__ do + x + y + z +end + +puts "done!" + +[実行結果] +x +y +done! +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `try` + +*B:* `catch` + +*C:* `catch :done` + +*D:* `rescue` + +----------------------------------------------------------------- + +**Q29. 以下の実行結果を出力するコードがあります。** + +``` +letters = catch(:done) do + ("a".."z").each do |a| + ("a".."z").each do |b| + ("a".."z").each do |c| + if a < b && b < c + __(1)__ + end + end + end + end +end + +puts letters.join + +[実行結果] +abc +``` +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `throw [a,b,c]` + +*B:* `throw [a,b,c], :done` + +*C:* `throw :done, [a,b,c]` + +*D:* `raise :done, [a,b,c]` + +----------------------------------------------------------------- + +**Q30. 以下の実行結果を出力するコードがあります。** + +``` +begin + __(1)__ +rescue + puts "OK" +end + +[実行結果] +OK +``` + +**__(1)__に入る適切な記述を選択してください。(2つ選択)** + +*A:* `raise StandardError` + +*B:* `raise Exception` + +*C:* `raise ArgumentError` + +*D:* `raise ScriptError` + +----------------------------------------------------------------- + +**Q31. 以下のコードがあります。** + +``` +AnError = Class.new(Exception) + +begin + raise AnError +rescue + puts "Bare rescue" +rescue StandardError + puts "StandardError rescue" +rescue AnError + puts "AnError rescue" +rescue Exception + puts "Exception rescue" +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* +``` +Bare rescue +``` + +*B:* +``` +StandardError rescue +``` + +*C:* +``` +AnError rescue +``` + +*D:* +``` +Exception rescue +``` + +*E:* +``` +AnError rescue +Exception rescue +``` + +----------------------------------------------------------------- + +**Q32. 以下のコードがあります。** + +``` +AnError = Class.new(Exception) + +begin + raise AnError +rescue + puts "Bare rescue" +rescue StandardError + puts "StandardError rescue" +rescue Exception + puts "Exception rescue" +rescue AnError + puts "AnError rescue" +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* +``` +Bare rescue +``` + +*B:* +``` +StandardError rescue +``` + +*C:* +``` +AnError rescue +``` + +*D:* +``` +Exception rescue +``` + +*E:* +``` +Exception rescue +AnError rescue +``` + +----------------------------------------------------------------- + +**Q33. 以下のコードがあります。** + +``` +begin + "hello".world +rescue => ex + p ex.class +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* `StandardError` + +*B:* `Exception` + +*C:* `NameError` + +*D:* `NoMethodError` + +*E:* `ArgumentError` + +----------------------------------------------------------------- + +**Q34. 以下のコードがあります。** + +``` +CustomError = Class.new(StandardError) + +def boom + raise CustomError +rescue + raise +end + +begin + boom +rescue => e + p e.class +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* `CustomError` + +*B:* `StandardError` + +*C:* `Exception` + +*D:* `RuntimeError` + +*E:* `SyntaxError` + +----------------------------------------------------------------- + +**Q35. 以下のコードがあります。** + +``` +def greeting + "hello" +ensure + puts "Ensure called!" + + "hi" +end + +puts greeting +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* + +``` +hello +``` + +*B:* + +``` +hi +``` + + +*C:* + +``` +Ensure called! +hello +``` + +*D:* + +``` +Ensure called! +hi +``` + +----------------------------------------------------------------- + +**Q36. 以下のコードがあります。** + +``` +class Identity + def self.this_object + self + end + + def this_object + self + end +end + +a = Identity.this_object +b = Identity.this_object + +c = Identity.new.this_object +d = Identity.new.this_object + +p a == b +p c == d +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* + +``` +true +true +``` + +*B:* +``` +true +false +``` + +*C:* +``` +false +true +``` + +*D:* +``` +false +false +``` + +----------------------------------------------------------------- + +**Q37. 以下のコードがあります。** + +``` +class Identity + def self.this_object + self.class + end + + def this_object + self + end +end + +p Identity.this_object.class +p Identity.new.this_object.class +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* +``` +Identity +Identity +``` + +*B:* +``` +Class +Identity +``` + +*C:* +``` +Object +Identity +``` + +*D:* +``` +Class +Object +``` + +----------------------------------------------------------------- + +**Q38. 以下のコードがあります。** + +``` +module Mixin + def this_object + self + end +end + +class Identity + include Mixin +end + + +p Identity.new.this_object.class +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* `Mixin` + +*B:* `Class` + +*C:* `Object` + +*D:* `Identity` + +----------------------------------------------------------------- + +**Q39: `Class`の直接のスーパークラスを選択してください。(1つ選択)** + +*A:* `Object` + +*B:* `Module` + +*C:* `BasicObject` + +*D:* `Class` + +----------------------------------------------------------------- + +**Q40. 以下のコードがあります。** + +``` +module Mixin + def self.greet + puts "Hello World!" + end +end + +class SomeClass + include Mixin +end +``` + +**以下の記述のうち正しいものを選択してください。(1つ選択)** + +*A:* `Mixin.greet`は`Hello World!`を出力し、`SomeClass.greet`は例外を発生する。 + +*B:* `Mixin.greet`は例外を発生し、`SomeClass.greet`は`Hello World!`を出力する。 + +*C:* `Mixin.greet`も`SomeClass.greet`も`Hello World!`を出力する。 + +*D:* `Mixin.greet`も`SomeClass.greet`も`Hello World!`を例外を発生する。 + +----------------------------------------------------------------- + +**Q41. 以下の実行結果を出力するコードがあります。** + +``` +module Mixin + def greet + puts "Hello World!" + end +end + +class SomeClass + extend Mixin +end + +__(1)__ + +[実行結果] +Hello World! +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `Mixin.greet` + +*B:* `SomeClass.new.greet` + +*C:* `SomeClass.greet` + +*D:* `Mixin.new.greet` + +----------------------------------------------------------------- + +**Q42. 以下の実行結果を出力するコードがあります。** + +``` +module Mixin + def greet + puts "Hello World!" + end +end + +class SomeClass + include Mixin +end + +__(1)__ + +[実行結果] +Hello World! +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `Mixin.greet` + +*B:* `SomeClass.new.greet` + +*C:* `SomeClass.greet` + +*D:* `Mixin.new.greet` + +----------------------------------------------------------------- + +**Q43. 以下の実行結果を出力するコードがあります。** + +``` +class BaseClass + private + + def greet + puts "Hello World!" + end +end + +class ChildClass < BaseClass + __(1)__ +end + + +ChildClass.new.greet + +[実行結果] +Hello World! +``` + +**__(1)__に入る記述として不適切なものを選択してください。(1つ選択)** + +*A:* + +``` +public :greet +``` + +*B:* + +``` +protected :greet +``` + +*C:* + +``` +def greet + super +end +``` + +*D:* + +``` +alias_method :original_greet, :greet + +def greet + original_greet +end +``` + +----------------------------------------------------------------- + +**Q44. 以下の実行結果を出力するコードがあります。** + +``` +h = [1, 2, 3] +case h +__(1)__ [x, y] + p [:two, x, y] +__(1)__ [x, y, z] + p [:three, x, y, z] +end + +[実行結果] +[:three, 1, 2, 3] +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `when` + +*B:* `in` + +*C:* `if` + +*D:* `=>` + +----------------------------------------------------------------- + +**Q45. 以下の実行結果を出力するコードがあります。** + +``` +class Alphabet + include Enumerable + + def initialize + @letters = ("A".."Z").to_a + end + + def __(1)__ + @letters.each do |e| + yield e + end + end +end + +set = Alphabet.new + +p set.take(5) +p set.select { |e| e > "W" } + +[実行結果] +["A", "B", "C", "D", "E"] +["X", "Y", "Z"] +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `all` + +*B:* `each` + +*C:* `to_a` + +*D:* `to_ary` + +*E:* `to_enum` + +----------------------------------------------------------------- + +**Q46. 以下のコードがあります。** + +``` +class TShirt + SIZES = [:xs, :s, :m, :l, :xl, :xxl] + + include Comparable + + def initialize(size) + @size = size + end + + attr_reader :size + + def <=>(other) + SIZES.index(size) <=> SIZES.index(other.size) + end +end + +medium = TShirt.new(:m) +large = TShirt.new(:l) + +p medium == large +p medium < large +p medium <= large +p medium > large +p medium >= large +``` +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* + +``` +true +false +true +false +true +``` + +*B:* +``` +false +true +true +false +false +``` + +*C:* +``` +false +false +false +true +true +``` + +*D:* +``` +false +false +false +false +false +``` + +*E:* +例外が発生する + +----------------------------------------------------------------- + +**Q47. 以下のコードがあります。** + +``` +require "date" + +date = Date.new(2000, 2, 24) + +puts(date << 12) +puts(date >> 12) +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*A:* +``` +2000-02-12 +2000-03-07 +``` + +*B:* +``` +2000-03-07 +2000-02-12 +``` + +*C:* +``` +1999-02-24 +2001-02-24 +``` + +*D:* +``` +1988-02-24 +2012-02-24 +``` + +----------------------------------------------------------------- + +**Q48. 以下の実行結果を出力するコードがあります。** + +``` +require "time" + +t = Time.__(1)__("00000024021993", "%S%M%H%d%m%Y") +puts t.iso8601 + +[実行結果] +1993-02-24T00:00:00+09:00 +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `format` + +*B:* `parse` + +*C:* `strftime` + +*D:* `strptime` + +----------------------------------------------------------------- + +**Q49. 以下の実行結果を出力するコードがあります。** + +``` +require "singleton" + +class Foo + __(1)__ +end + +x = Foo.instance +y = Foo.instance +p x.equal?(y) + +[実行結果] +true +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `include Singleton` + +*B:* `extend Singleton` + +*C:* `using Singleton` + +*D:* `singletonize` + +----------------------------------------------------------------- + +**Q50. 以下の実行結果を出力するコードがあります。** + +``` +require 'forwardable' + +class List + extend Forwardable + + def initialize + @contents = [] + end + + __(1)__ :@contents, :push + __(1)__ :@contents, :[] +end + +list = List.new +list.push("a") +list.push("b") +list.push("c") +p list[1] + +[実行結果] +"b" +``` + +**__(1)__に入る適切な記述を選択してください。(1つ選択)** + +*A:* `forward` + +*B:* `def_forwarder` + +*C:* `def_delegator` + +*D:* `define` + +----------------------------------------------------------------- + diff --git a/silver.md b/silver.md index 5d0175c..975c407 100644 --- a/silver.md +++ b/silver.md @@ -57,7 +57,7 @@ puts num **Which is the correct output? (Choose one.)** - (a) `nil` -- (b) `025` +- (b) `025` - (c) `21` - (d) `25` @@ -74,7 +74,7 @@ p y **Which is the correct output? (Choose one.)** - (a) 1 -- (b) 2 +- (b) 2 - (c) "Hello" - (d) true @@ -97,7 +97,7 @@ p size - (a) `"S"` - (b) `"M"` -- (c) `"L"` +- (c) `"L"` - (d) `"XL"` **Which is the correct output? (Choose one.)** @@ -164,44 +164,53 @@ p x --------------------------------------------------------------------------- -**Q10. Which of the following are correct to specify Windows-1252 as the encoding of the source code? (Choose all that apply.)** +**Q10. Given the following:** -- (a) `# charset: Windows-1252` -- (b) `# chars: Windows-1252` -- (c) `# coding: Windows-1252` -- (d) `# encoding: Windows-1252` +``` +s = "abcde" +p s.each_char.map { |i| + i * 2 +} +``` + +**Which is the correct result? (Choose one)** + +- (a) `[97, 98, 99, 100, 101]` +- (b) `[194, 196, 198, 200, 202]` +- (c) `["a", "b", "c", "d", "e"]` +- (d) `["aa", "bb", "cc", "dd", "ee"]` +- (e) An error occurs at run-time. --------------------------------------------------------------------------- **Q11. Given the following:** ``` -# coding: Windows-1252 - -puts "hello".encoding.name +p "cocoa".chars.tally ``` **Which is the correct result? (Choose one)** -- (a) ASCII-8BIT -- (b) UTF-8 -- (c) Windows-1252 -- (d) A syntax error occurs. +- (a) `{99=>2, 111=>2, 97=>1}` +- (b) `{?c=>2, ?o=>2, ?a=>1}` +- (c) `{"c"=>2, "o"=>2, "a"=>1}` +- (d) An error occurs at run-time. --------------------------------------------------------------------------- -**Q12. Given the following:** +**Q12. Which of the following can be inserted into `__(1)__` in order to generate the output below? (Choose one.)** ``` -puts "hello".encoding.name -``` +puts "blah blah blah".__(1)__(/blah/, "yay") -**Which is the correct result? (Choose one.)** +[Output] +yay yay yay +``` -- (a) ASCII-8BIT -- (b) UTF-8 -- (c) Windows-1252 -- (d) A syntax error occurs. +- (a) `sub` +- (b) `gsub` +- (c) `replace` +- (d) `replace_all` --------------------------------------------------------------------------- @@ -231,64 +240,84 @@ end **Q14: Given the following:** ``` -s = "daikon" - -if s.empty? - puts "blank" -elsif s.length < 5 - puts "short" -else - puts "long" +["foo: abc", "bar: 100"].each do |i| + p i.slice(/[0-9]+/)&.to_i end ``` **Which is the correct result? (Choose one.)** -- (a) blank -- (b) short -- (c) long -- (d) An exception is raised. +*(a)* +``` +0 +100 +``` + +*(b)* +``` +nil +100 +``` + +*(c)* +``` +false +100 +``` + +*(d)* +A syntax error occurs. + +*(e)* +An error occurs at run-time. --------------------------------------------------------------------------- -**Q15: Which of the following can be inserted into `__(1)__` in order for the given code to generate the output below? (Choose one.)** +**Q15: Given the following:** ``` -n = 42 -if n < 0 - puts "a" -__(1)__ n > 0 - puts "b" -else - puts "c" +def foo(x: 1, y: 2, z: 3) + p [x, y, z] end -[Output] -b +foo(y: 4, z: 5) ``` -- (a) `elseif` -- (b) `else if` -- (c) `elif` -- (d) `elsif` +**Which is the correct result? (Choose one.)** +- (a) `[1, 2, 3]` +- (b) `[1, 4, 5]` +- (c) A syntax error occurs. +- (d) An error occurs at run-time. + --------------------------------------------------------------------------- -**Q16. Which of the following regular expressions only match the string "Ruby" or "ruby"? (Choose two.)** +**Q16: Which of the following can be inserted into `__(1)__` in order for the given code to generate the output below? (Choose one.)** -- (a) `/\A[Rr]uby\z/` -- (b) `/\ARuby|ruby\z/` -- (c) `/\A[Rr][u][b][y]\z/` -- (d) `/\AR|ruby\z/` +``` +def foo(x:, y:, z:) + p [x, y, z] +end + +h = {x: 1, y: 2, z: 3} +__(1)__ +[Output] +[1, 2, 3] +``` + +- (a) `foo(*h)` +- (b) `foo(**h)` +- (c) `foo(&h)` +- (d) `foo(^h)` --------------------------------------------------------------------------- -**Q17. Which of the following regular expressions has a match only when a string has at least one character, and consists of lowercase letters only? (Choose one.)** +**Q17. Which of the following regular expressions only match the string "Ruby" or "ruby"? (Choose two.)** -- (a) `/\A[a-z]*\z/` -- (b) `/\A[a-z][a-z]*\z/` -- (c) `/\A[a-z][^a-z]*\z/` -- (d) `/\A[a-z][a-z].\z/` +- (a) `/\A[Rr]uby\z/` +- (b) `/\ARuby|ruby\z/` +- (c) `/\A[Rr][u][b][y]\z/` +- (d) `/\AR|ruby\z/` --------------------------------------------------------------------------- @@ -302,7 +331,7 @@ p MSG **What is the correct result? (Choose one.)** -- (a) `47` is displayed without warning. +- (a) `47` is displayed without warning. - (b) An error occurs because MSG is a constant. - (c) `42` is displayed because MSG is a constant. - (d) A warning appears beacuse MSG is a constant but `47` is displayed. @@ -320,17 +349,17 @@ p MSG **What is the correct result? (Choose one.)** - (a) An error occurs because MSG is a constant. -- (b) `HELLO` is displayed without warning. -- (c) A warning apears because MSG is a constant but "HELLO" is displayed +- (b) `HELLO` is displayed without warning. +- (c) A warning apears because MSG is a constant but `HELLO` is displayed - (d) `hello` is displayed since MSG is a constant. --------------------------------------------------------------------------- **Q20. Which of the following statements are true? (Choose two.):** -- (a) Local variables start with a lower case letter, and are two or more characters in length. -- (b) Global variables start with $. -- (c) Instance variables start with *. +- (a) Local variables start with a lower case letter, and are two or more characters in length. +- (b) Global variables start with $. +- (c) Instance variables start with *. - (d) Class variables start with $. - (e) Constants start with an upper case letter. @@ -351,26 +380,26 @@ p y *(a)* ``` -[1,3,5,7] -[1,2,3,4,5,6,7,8] +[1, 3, 5, 7] +[1, 2, 3, 4, 5, 6, 7, 8] ``` *(b)* ``` -[1,2,3,4,5,6,7,8] -[1,2,3,4,5,6,7,8] +[1, 2, 3, 4, 5, 6, 7, 8] +[1, 2, 3, 4, 5, 6, 7, 8] ``` *(c)* ``` -[1,3,5,7] -[1,3,5,7] +[1, 3, 5, 7] +[1, 3, 5, 7] ``` *(d)* ``` -[1,3,5,7] -[2,4,6,8] +[1, 3, 5, 7] +[2, 4, 6, 8] ``` --------------------------------------------------------------------------- @@ -385,9 +414,9 @@ a.push(12) p a ``` -- (a) `[2, 4, 6, 8, 10, 12]` -- (b) `[2, 4, 6, 8, 10]` -- (c) `[4, 6, 8, 12]` +- (a) `[2, 4, 6, 8, 10, 12]` +- (b) `[2, 4, 6, 8, 10]` +- (c) `[4, 6, 8, 12]` - (d) `[4, 6, 8]` **Which is the correct output? (Choose one.)** @@ -426,7 +455,7 @@ p n - (a) `true` - (b) `false` -- (c) `nil` +- (c) `nil` - (d) A syntax error occurs. --------------------------------------------------------------------------- @@ -441,27 +470,28 @@ p __(1)__ [7, 5, 3] ``` -- (a) `x[1, 3]` +- (a) `x[1, 3]` - (b) `x[1..-1]` - (c) `x[-3..-1]` -- (d) `x[-4..-2]` +- (d) `x[-4..-2]` --------------------------------------------------------------------------- -**Q26. Which of the following can be inserted into __(1)__ in order for the given code to generate the output below? (Choose one.)** +**Q26. Which of the following can be inserted into __(1)__ in order for the given code to generate the output below? (Choose two.)** ``` -ary = [ "apple", "banana", "carrot" ] -p ary.__(1)__(",") +ary = [ 1, 2, 3, 4, 5 ] +p ary.__(1)__ { |i| i.odd? } [Output] -"apple,banana,carrot" +[1, 3, 5] ``` -- (a) `concat` -- (b) `map` -- (c) `select` -- (d) `join` +- (a) `collect` +- (b) `select` +- (c) `map` +- (d) `filter` +- (e) `filter_map` --------------------------------------------------------------------------- @@ -473,24 +503,24 @@ puts "42A7".to_i **What is the correct result? (Choose one)** -- (a) 42 -- (b) 42A7 +- (a) 42 +- (b) 42A7 - (c) 17063 - (d) An error occurs at run-time. --------------------------------------------------------------------------- -**Q28. Which of the following methods will NOT show you if the element 'c' exists in the hash key or not? (Choose one.)** +**Q28. Which of the following methods will NOT show you if the element `:c` exists in the hash key or not? (Choose one.)** ``` -h = {"a"=>2, "b"=>4, "c"=>6, "d"=>8, "e"=>10} +h = {a: 2, b: 4, c: 6, d: 8, e: 10} ``` -- (a) `p h.has_key?('c')` -- (b) `p h.contain?('c')` -- (c) `p h.include?('c')` -- (d) `p h.key?('c')` -- (e) `p h.member?('c')` +- (a) `p h.has_key?(:c)` +- (b) `p h.contain?(:c)` +- (c) `p h.include?(:c)` +- (d) `p h.key?(:c)` +- (e) `p h.member?(:c)` --------------------------------------------------------------------------- @@ -502,11 +532,11 @@ a.__(1)__ p a [Output] -[120,80,160,180] +[120, 80, 160, 180] ``` -- (a) `reject! {|i| i < 80}` -- (b) `slice {|i| i < 80 }` +- (a) `reject! {|i| i < 80}` +- (b) `slice {|i| i < 80 }` - (c) `slice! {|i| i < 80}` - (d) `delete_if! {|i| i < 80}` - (e) `delete_if {|i| i < 80}` @@ -524,27 +554,25 @@ p ["apple", "banana"] __(1)__ ["banana", "carrot"] ``` - (a) `.concat` -- (b) `&` +- (b) `&` - (c) `|` -- (d) `||` +- (d) `||` --------------------------------------------------------------------------- -**Q31. Which of the following can be inserted into `__(1)__` in order for the given code to generate the output below? (Choose one.)** +**Q31. Given the following:** ``` -p ["apple", "banana"] __(1)__ ["banana", "carrot"] - -[Output] -["banana"] +p %i(x1 x2 x3) ``` -- (a) `|` -- (b) `||` -- (c) `&&` -- (d) `&` -- (e) `.concat` +What is the correct result? (Choose one.) + +- (a) `"x1 x2 x3"` +- (b) `[1, 2, 3]` +- (c) `["x1", "x2", "x3"]` +- (d) `[:x1, :x2, :x3]` --------------------------------------------------------------------------- @@ -569,9 +597,9 @@ end What is the correct result? (Choose one.) -- (a) A syntax error -- (b) `SomeError` -- (c) `SomeErrorSomeOtherError` +- (a) A syntax error +- (b) `SomeError` +- (c) `SomeErrorSomeOtherError` - (d) `SomeOtherError` --------------------------------------------------------------------------- @@ -601,7 +629,7 @@ DONE! *(b)* ``` -Error: ZeroDivisionError +Error: ZeroDivisionError ``` *(c)* @@ -624,7 +652,7 @@ Error: ZeroDivisionError - (a) an `UndefinedParentClassError` exception is raised - (b) a syntax error occurs -- (c) the `Module` class becomes the superclass. +- (c) the `Module` class becomes the superclass. - (d) the class is created without a superclass. - (e) the `Object` class becomes the superclass. @@ -645,8 +673,8 @@ end **What is the correct result? (Choose one.)** - (a) No output. -- (b) An error occurs at run-time. -- (c) "MOO!" +- (b) An error occurs at run-time. +- (c) `MOO!` - (d) `nil` --------------------------------------------------------------------------- @@ -671,7 +699,7 @@ g.greet HELLO, WORLD! ``` -- (a) `Shouter` +- (a) `Shouter` - (b) `new` - (c) `initialize` - (d) `__init__` @@ -728,28 +756,27 @@ puts bar.var **What is the correct result? (Choose one.)** - -- (a) apple + +- (a) apple - (b) banana -- (c) No output. +- (c) No output. - (d) An error occurs at run-time. --------------------------------------------------------------------------- -**Q39. Given the following:** +**Q39. Which of the following can be inserted into `__(1)__` in order for the given code to generate the output below? (Choose two.)** ``` -ary = [4,2,8,4,2,8,4,2,8] -ary.delete(8) -p ary -``` +puts "$foo$".__(1)__("$") -Which is the correct output? (Choose one.) +[Output] +foo$ +``` -- (a) `[4, 2, 8, 4, 2, 8, 4, 2]` -- (b) `[4, 2, 8, 4, 2, 8, 4, 2, 8]` -- (c) `[4, 2, 4, 2, 4, 2]` -- (d) `[8]` +- (a) `sub` +- (b) `chop` +- (c) `delete` +- (d) `delete_prefix` --------------------------------------------------------------------------- @@ -763,10 +790,8 @@ p r.__(1)__ ["a", "b", "c", "d", "e"] ``` -**Which is the correct output? (Choose one.)** - -- (a) `array` -- (b) `to_ary` +- (a) `array` +- (b) `to_ary` - (c) `to_a` - (d) `to_array` @@ -781,7 +806,7 @@ p [0,1,2,3,4,5].find {|x| x < 3} **Which is the correct output? (Choose one.)** - (a) `[0, 1, 2]` -- (b) `0` +- (b) `0` - (c) `[0, 1, 2, 3]` - (d) `true` @@ -799,7 +824,7 @@ p [1,16,8,4,2].__(1)__ - (a) `sort_by { |x| -x }` - (b) `sort_reverse` -- (c) `sort.reverse` +- (c) `sort.reverse` - (d) `reverse.sort` --------------------------------------------------------------------------- @@ -824,20 +849,19 @@ p ary.__(1)__ **Q44. Given the following:** ``` -file = File.new("test") -file.seek(5) -print file.gets - -[Contents of file test] -hellorubyworld +File.write("test", "hellorubyworld\n") +File.open("test") do |file| + file.seek(5) + print file.gets +end ``` **Which is the correct output? (Choose one.)** -- (a) hello -- (b) rubyworld -- (c) hellor -- (d) rubyw +- (a) hello +- (b) rubyworld +- (c) hellor +- (d) rubyw - (e) orubyworld --------------------------------------------------------------------------- @@ -848,12 +872,12 @@ hellorubyworld file = open("sample.txt") ``` -- (a) `r` +- (a) `r` - (b) `r+` - (c) `a` -- (d) `a+` -- (e) `w` -- (f) `w+` +- (d) `a+` +- (e) `w` +- (f) `w+` --------------------------------------------------------------------------- @@ -872,7 +896,7 @@ open("test_one.txt") {|source| - (a) `r+` - (b) `a` - (c) `a+` -- (d) `w` +- (d) `w` - (e) `w+` --------------------------------------------------------------------------- @@ -895,7 +919,7 @@ p "hello ruby world"[6,4] **What is the correct result? (Choose one.)** -- (a) `"hello "` +- (a) `"hello "` - (b) `"ruby"` - (c) `" world"` - (d) An error occurs at run-time. @@ -904,19 +928,19 @@ p "hello ruby world"[6,4] **Q49:** -``` Given the following: +``` str = "bat" str[1,1] = "o" p str +``` Which is the correct output? (Choose one.) -``` -- (a) `"boo"` -- (b) `"bot"` -- (c) `"oat"` +- (a) `"boo"` +- (b) `"bot"` +- (c) `"oat"` - (d) `"o"` --------------------------------------------------------------------------- @@ -929,9 +953,9 @@ puts 5 * "hi" **What is the correct result? (Choose one.)** -- (a) `"hihihihihi"` -- (b) An error occurs at run-time. -- (c) `"5hi"` +- (a) `"hihihihihi"` +- (b) An error occurs at run-time. +- (c) `"5hi"` - (d) `"5*hi"` --------------------------------------------------------------------------- diff --git a/silver_answers.md b/silver_answers.md index 61b035d..bb74a5f 100644 --- a/silver_answers.md +++ b/silver_answers.md @@ -9,7 +9,7 @@ logically false, all other objects are treated as logically true. **A2:** (c) and (e) -The complete list of reserved words as of Ruby 2.1 is listed below: +The complete list of reserved words as of Ruby 3.1 is listed below: ![Ruby keywords](ruby-keywords.png) @@ -17,7 +17,7 @@ The complete list of reserved words as of Ruby 2.1 is listed below: **A3:** (c) -Ruby variable names must begin with a lowercase letter or underscore, and may contain only letters, numbers, and underscore characters. +Ruby variable names must begin with a lowercase letter or underscore, and may contain only letters, numbers, underscore, and non-ASCII characters. Variable names must not conflict with keywords (e.g. you cannot have a variable called `class`), but unambiguous names that contain reserved words are acceptable (i.e. both `classy` and `_class` are valid Ruby variable names) @@ -74,71 +74,75 @@ Although block variables with the same name of local variables from the surround --------------------------------------------------------------------------- -**A10:** (c), (d) +**A10:** (d) -The encoding _magic comment_ must appear as the first line of the file, unless a UNIX shebang line is present (in that case, the encoding line would be placed on the second line). +[String#each_char](https://docs.ruby-lang.org/en/3.1/String.html#method-i-each_char) returns an [Enumerator](https://docs.ruby-lang.org/en/3.1/Enumerator.html) which yields each character in the receiver. Note that characters are represented by single character strings. -Both `coding: ...` and `encoding: ...` may be used to set the source file's encoding, and they work identically. +[Enumerable#map](https://docs.ruby-lang.org/en/3.1/Enumerable.html#method-i-map) returns an array of objects returned by the given block. -Setting the encoding for a source file affects only the contents of that file. In other words, it applies to things like string literals in the file, but does not automatically set encoding for things like reading from and to other files. +`string * integer` returns a string containing `integer` copies of `string`. -If no encoding comment is present in a file, the default encoding is set to UTF-8. +Therefore, `s.each_char.map { |i| i * 2}` evaluates to `["aa", "bb", "cc", "dd", "ee"]`. --------------------------------------------------------------------------- **A11:** (c) -`String#encoding` returns an `Encoding` object which also provides some other helpful methods (e.g. `Encoding#ascii_compatible?`) +[String#chars](https://docs.ruby-lang.org/en/3.1/String.html#method-i-chars) returns an array of characters in the receiver. Note that characters are represented by single character strings. + +[Enumerable#tally](https://docs.ruby-lang.org/en/3.1/Enumerable.html#method-i-tally) returns a hash containing the counts of equal elements. + +Therefore, `"cocoa".chars.tally` evaluates to `{"c"=>2, "o"=>2, "a"=>1}`. --------------------------------------------------------------------------- **A12:** (b) -When a `coding:` comment is omitted, Ruby will use UTF-8 by default for its source encoding. +[String#gsub](https://docs.ruby-lang.org/en/3.1/String.html#method-i-gsub) returns a copy of the receiver with all occurrences of the given pattern replaced. ---------------------------------------------------------------------------- -**A13:** (b) +[String#sub](https://docs.ruby-lang.org/en/3.1/String.html#method-i-sub) returns a copy of the receiver with only the first occurrence of the given pattern replaced. -In an `if/elsif/else` conditional statement, the first matching `if` or `elsif` branch will be executed. If none match, then the `else` branch will be run. +[String#replace](https://docs.ruby-lang.org/en/3.1/String.html#method-i-replace) replaces the contents of the receiver with the contents of the given string. + +String does not have `#replace_all` method. --------------------------------------------------------------------------- -**A14.** (c) +**A13:** (b) -When none of the `if` and `elsif` clauses of a conditional statement match, the `else` branch is run. +In an `if/elsif/else` conditional statement, the first matching `if` or `elsif` branch will be executed. If none match, then the `else` branch will be run. --------------------------------------------------------------------------- -**A15: (d)** +**A14:** (b) -Nearly every programming language has some sort of `if/elsif/else` structure, but they vary in the name they choose for `elsif`. This can be a source of confusion if you're coming to Ruby from another language, and the only solution is to memorize the specific term used in each language. +[String#slice](https://docs.ruby-lang.org/en/3.1/String.html#method-i-slice) returns the first matching substring found in the receiver, or `nil` if none found. +`&.` is called [safe nagivation operator](https://docs.ruby-lang.org/en/3.1/syntax/calling_methods_rdoc.html#label-Safe+Navigation+Operator). `x&.foo` invokes `foo` on `x` if `x` is not `nil`. If `x` is `nil`, `x&.foo` does not invoke `foo` and evaluates to `nil`. --------------------------------------------------------------------------- -**A16: (a) and (c)** +**A15: (b)** -Character classes (`[...]`) match any single character from within the brackets. +If any [keyword arguments](https://docs.ruby-lang.org/en/3.1/syntax/calling_methods_rdoc.html#label-Keyword+Arguments) are not given, the default value from the method definition will be used. -Alternatives (`...|...`) are used to match any one of many possible subexpressions. +--------------------------------------------------------------------------- -The `\A` anchor matches the beginning of a string, and the `\z` anchor matches the end of a string. +**A16: (b)** -_Note that the reason that (b) is not a correct answer is because its subexpressions are `\ARuby` and `ruby\z`, allowing matches for things like `Ruby123`_ +`**` turns a Hash into [keyword arguments](https://docs.ruby-lang.org/en/3.1/syntax/calling_methods_rdoc.html#label-Keyword+Arguments). --------------------------------------------------------------------------- -**A17: (b)** +**A17: (a) and (c)** -The expression `/\A[a-z][a-z]*\z/` could be described in words as "A string which begins with a lowercase letter, followed by zero or more additional lowercase letters and nothing else." +Character classes (`[...]`) match any single character from within the brackets. -Here are some additional notes for understanding the other patterns in this question: +Alternatives (`...|...`) are used to match any one of many possible subexpressions. -- The `*` quantifier matches a subexpression zero or more times. -- The `.` quantifier matches any character except a newline. -- The `^` inverts a character class, causing it to match anything except the named chars. +The `\A` anchor matches the beginning of a string, and the `\z` anchor matches the end of a string. -(see `A16` for a recap of other features that were already covered in that question) +_Note that the reason that (b) is not a correct answer is because its subexpressions are `\ARuby` and `ruby\z`, allowing matches for things like `Ruby123`_ --------------------------------------------------------------------------- @@ -150,7 +154,7 @@ Because Ruby also uses constants for referencing module and class names, the con --------------------------------------------------------------------------- -**A19. (b)** +**A19: (b)** No warning is shown because the constant is not being redefined; instead the object it references is being modified. @@ -166,7 +170,7 @@ Some notes on Ruby variable naming rules: - Class variables start with `@@`. - Instance variables start with `@`. - Local variables must begin with a lowercase letter or an underscore. -- The remaining characters in any variable type are limited to letters, numbers, and underscores. +- The remaining characters in any variable type are limited to letters, numbers, underscores, and non-ASCII characters. --------------------------------------------------------------------------- @@ -229,11 +233,10 @@ To clarify, here is a list of the index values for each position in the array fr --------------------------------------------------------------------------- -**A26: (d)** +**A26: (b) and (d)** -`Array#join` returns a string that is created by converting each element -in an array to a string and then combining them together with the -specified separator. +`Array#select` and `Array#filter` return elements for which the given block +returns a truthy value. --------------------------------------------------------------------------- @@ -273,15 +276,17 @@ The `|` operator is equivalent to a set union. It returns a new array that is bu **A31: (d)** -The `&` operator is equivalent to a set intersection. It returns a new array that is made up of elements found in both arrays it operates on, while preserving order and eliminating duplicates. +`%i(...)` is an non-interpolated array of symbols, separated by whitespace. + +See [documentation of percent literals](https://docs.ruby-lang.org/en/3.1/syntax/literals_rdoc.html#label-Percent+Literals) for details. --------------------------------------------------------------------------- **A32: (b)** -In a `begin/rescue/end` block... the first matched `rescue` statement will be executed. +In a `begin/rescue/end` block... the first matched `rescue` clause will be executed. -Because `SomeOtherError` is a subclass of `SomeError`, it matches the `rescue SomeError` statement, and so that branch is what gets run. +Because `SomeOtherError` is a subclass of `SomeError`, it matches the `rescue SomeError` clause, and so that branch is what gets run. In a real application, it is usually a good practice to attempt to match more specific errors before the more general errors that they inherit from (e.g. `rescue StandardError` would usually come last). @@ -335,13 +340,13 @@ In this particular example, calling `Bar.new` causes `Bar#initialize` to run, wh --------------------------------------------------------------------------- -**A39: (c)** +**A39: (d)** -`Array#delete` removes all elements from an array that are equal to the specified value. +[String#delete_prefix](https://docs.ruby-lang.org/en/3.1/String.html#method-i-delete_prefix) returns a copy of the receiver with a given prefix deleted. -For deleting a value at a particular index, see documentation for `Array#delete_at`. +`"$foo$".delete("$")` evaluates to `"foo"` because [String#delete](https://docs.ruby-lang.org/en/3.1/String.html#method-i-delete) returns a copy of the receiver with all characters specified by its arguments deleted. -For deleting values based on a condition, see documentation for `Array#delete_if` (an alias for `reject!`). +`sub("$")` and `chop("$")` raise ArgumentError because [String#sub](https://docs.ruby-lang.org/en/3.1/String.html#method-i-sub) takes two arguments and [String#chop](https://docs.ruby-lang.org/en/3.1/String.html#method-i-chop) takes no argument. --------------------------------------------------------------------------- diff --git a/silver_answers_ja.md b/silver_answers_ja.md new file mode 100644 index 0000000..500378e --- /dev/null +++ b/silver_answers_ja.md @@ -0,0 +1,477 @@ +**A1:** (a)および(b) + +Rubyではすべてのオブェクトが条件分岐で使用するための論理値を持ちます。 + +`false`と`nil`は論理的に偽として、それ以外のすべてのオブジェクトは論理的に真として扱われます。 + +--------------------------------------------------------------------------- + +**A2:** (c)および(e) + +Ruby 3.1の予約語の一覧は以下のとおりです。 + +![Ruby keywords](ruby-keywords.png) + +--------------------------------------------------------------------------- + +**A3:** (c) + +Rubyのローカル変数名は小文字またはアンダースコアではじまり、アルファベット、数字、アンダースコア、非ASCII文字のみからなります。 + +予約語を変数名として使用することはできません(例えば`class`という変数名は使用できません)が、予約語を含む変数名は許可されています(つまり`classy`や`_class`は有効な変数名です)。 + +--------------------------------------------------------------------------- + +**A4:** (a)および(b) + +シングルクォートの文字列リテラルはシンプルで、文字のそのままの列を表現します。 + +ダブルクォートの文字列リテラルはより複雑ですが、Rubyの式の評価結果を文字列中に埋め込む式展開(`#{...}`)のような機能を提供します。 + +グローバル変数の値を埋め込む場合は`#$`を省略記法として使用できます(同様にインスタンス変数の場合は`#@`を使用できます)。この省略記法はより一般的な`#{...}`記法に比べるとあまり使われていません。 + +--------------------------------------------------------------------------- + +**A5:** (c) + +整数リテラルの先頭の0は8進数表記を意味します。ただし、デフォルトでは10進数として出力が行われます。 + +10進数以外での出力を行うためには、さまざまな書式化数値出力機能が提供されています(例: `Strign#%`、`Numeric#to_s(base)`、`Kernel#printf`)。 + +--------------------------------------------------------------------------- + +**A6:** (b) + +三項演算子(`cond ? expr1 : expr2`)は`if/else`の省略形で、`cond`が真の場合`expr1`を、偽の場合`expr2`を返します。1行に収まるような短い文の記述に向いています。 + +--------------------------------------------------------------------------- + +**A7:** (a) + +`case`文は`when`の条件にマッチする最初の分岐を実行します。 + +Rubyの範囲リテラル`x..y`は、`y`の値を含みます。 + +したがって、`1..120`と`120..170`の両方が`120`を含み、`when 1..120`の分岐が最初にマッチして実行されます。 + +--------------------------------------------------------------------------- + +**A8:** (d) + +ブロックでは外側のスコープのローカル変数にアクセスすることができますが、ブロックパラメータ自体は常にブロックローカルです。これはブロックパラメータの名前が外側のローカル変数と同じ場合、ブロック内ではブロックローカル変数が参照されることを意味します。これによって、変数名が衝突した場合に外側のローカル変数を誤って変更することが防がれます。 + +外側のローカル変数と同名のブロックパラメータを定義することはアンチパターンと考えられ、プログラムの間違いのサインかもしれません。この問題を発見するには、`ruby`を`-w`オプション付きで実行し、`warning: shadowing outer local variable - item`のような警告を表示させるようにします。 + +--------------------------------------------------------------------------- + +**A9:** (c) + +`Integer#times`メソッドは0から指定された値より1つ小さい整数までの値を順番にブロックパラメータとして渡します。 + +ブロックパラメータと同名の外側のローカル変数は参照できません(A8参照)が、他のローカル変数はアクセス・変更できます。これはRubyのブロックはクロージャであるためです。 + +--------------------------------------------------------------------------- + +**A10:** (d) + +[String#each_char](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_EACH_CHAR)はレシーバのそれぞれの文字をyieldする[Enumerator](https://docs.ruby-lang.org/en/3.1/Enumerator.html)を返します。文字は1文字のも文字列で表現されることに注意してください。 + +[Enumerable#map](https://docs.ruby-lang.org/ja/3.1/class/Enumerable.html#I_MAP) は与えられたブロックの値の配列を返します。 + +`string * integer`は`string`を`integer`回コピーして連結した値を返します。 + +したがって、`s.each_char.map { |i| i * 2}`の評価結果は`["aa", "bb", "cc", "dd", "ee"]`になります。 + +--------------------------------------------------------------------------- + +**A11:** (c) + +[String#chars](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_CHARS)はレシーバのすべての文字の配列を返します。文字は1文字のも文字列で表現されることに注意してください。 + +[Enumerable#tally](https://docs.ruby-lang.org/ja/3.1/class/Enumerable.html#I_TALLY)は値が同じ要素の数を含むハッシュを返します。 + +したがって、`"cocoa".chars.tally`の評価結果は`{"c"=>2, "o"=>2, "a"=>1}`になります。 + +--------------------------------------------------------------------------- + +**A12:** (b) + +[String#gsub](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_GSUB)はパターンにマッチするすべての部分を置換した文字列を返します。 + + +[String#sub](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_SUB)はパターンにマッチする最初の部分を置換した文字列を返します。 + +[String#replace](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_REPLACE) は与えられた文字列でレシーバの内容を置き換えます。 + +Stringに`#replace_all`メソッドはありません。 + +--------------------------------------------------------------------------- + +**A13:** (b) + +`if/elsif/else`文では、最初に条件を満たした`if`または`elsif`の分岐が実行されます。いずれも条件を満たさない場合は、`else`の分岐が実行されます。 + +--------------------------------------------------------------------------- + +**A14:** (b) + +[String#slice](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_SLICE)は最初にマッチした部分文字列を返します。マッチしなかった場合は`nil`を返します。 +`x&.foo`は`x`が`nil`でない場合`x`に対して`foo`メソッドを呼び出します。`x`が`nil`の場合、`x&.foo`はメソッドを呼び出さず、`nil`を返します。 + +--------------------------------------------------------------------------- + +**A15: (b)** + +キーワード引数が与えられなかった場合、メソッド定義のデフォルト値が使用されます。 + +--------------------------------------------------------------------------- + +**A16: (b)** + +`**` はHashをキーワード引数に変換します。 + +--------------------------------------------------------------------------- + +**A17: (a)および(c)** + +文字クラス(`[...]`)はブラケット内のいずれかの文字にマッチします。 + +選択(`...|...`)は複数の部分式のいずれかにマッチします。 + +`\A`アンカーは文字列の先頭に、`\z`アンカーは文字列の末尾にマッチします。 + +(b)が正解でないのは、(b)の部分式は`\ARuby`と`ruby\z`であり、`Ruby123`のような文字列にもマッチしてしまうためです。 + +--------------------------------------------------------------------------- + +**A18: (d)** + +定数は再定義できますが、通常あまり好ましくないため、警告が表示されます。 + +Rubyでは定数はモジュールやクラスの名前にも使用されるため、定数の再定義に関する警告は意図しない名前の衝突を防ぐために有用です。 + +--------------------------------------------------------------------------- + +**A19: (b)** + +定数は再定義されず、定数から参照されるオブジェクトの内容が変更されているだけなので、警告は表示されません。 + +慣習的に定数から参照されるオブジェクトは変更されないものとして扱われますが、その慣習があてはまらないレアケースもあります。 + +--------------------------------------------------------------------------- + +**A20: (b)および(e)** + +Rubyの変数名についてのルールは以下のとおりです。 + +- グローバル変数は`$`ではじまります。 +- クラス変数は`@@`ではじまります。 +- インスタンス変数は`@`ではじまります。 +- ローカル変数は小文字またはアンダースコアではじまります。 +- 残りの文字はアルファベット、数字、アンダースコア、非ASCII文字に限定されます。 + +--------------------------------------------------------------------------- + +**A21: (c)** + +この例では、`x`と`y`は両方とも同じ配列オブジェクトを参照します。 + +`Array#reject!`はレシーバを変更するため、両方の変数から参照される一つの配列が変更が変更されるということを意味します。 + +--------------------------------------------------------------------------- + +**A22: (c)** + +以下のような配列操作があります。 + +- `shift`は配列の最初の要素を削除し、その要素を返します。 +- `pop`は配列の最後の要素を削除し、その要素を返します。 +- `push`は配列の末尾に指定された要素を追加します。 + +--------------------------------------------------------------------------- + +**A23: (b)** + +論理演算子`||`と`&&`は短絡評価され、必要な場合だけ右辺が評価されます。 + +真理値オブジェクトのために`|`と`&`が提供されており、これらは短絡評価を行わず、常に右辺が評価されます。 + +`||`と`&&`はすべてのオブジェクトに対して使用できますが、`|`と`&`は実装されていないオブジェクトもあることに注意してください。 + +--------------------------------------------------------------------------- + +**A24: (c)** + +`or`演算子は短絡評価され`n = true`という式は実行されませんが、ローカル変数`n`は静的に宣言されます。したがって、変数は存在しますが、その値は`nil`です。 + +--------------------------------------------------------------------------- + +**A25: (a)および(d)** + +この問題では部分配列を指定する二つの異なる方法を示しています。 + +一つのアプローチは二つの整数を使用する方法、つまり`x[1,3]`のような書き方で、これはインデックス`1`からはじまる長さ`3`の部分配列を意味します。 + +Another approach is to use a range, which generates a subarray based the index values within that range. +もう一つのアプローチはRangeオブジェクトを使用する方法で、指定された範囲に含まれるインデックスの値にもとづいた部分配列を生成します。 + +範囲を使うシンプルな形式は`x[1..3]`のようなもので、インデックス`1`ではじまり`3`で終わる部分配列を返します。 + +しかし、Rubyでは負のインデックスも許可されており、配列の先頭からではなく末尾からのインデックスとして使用されます。 + +したがって、`x[-4..-2]`は配列の末尾から4番目から末尾から2番目までの部分配列を返します。 + +インデックスの意味を明確にするため、この問題の配列の各要素に対応するインデックスの値を以下に示します。 + +``` + x [ 9, 7, 5, 3, 1] + i 0 1 2 3 4 +-i -5 -4 -3 -2 -1 +``` + +--------------------------------------------------------------------------- + +**A26: (b)および(d)** + +`Array#select`と`Array#filter`は与えられたブロックが真の値を返す要素の配列を返します。 + +--------------------------------------------------------------------------- + +**A27: (a)** + +`String#to_i`は先頭の文字から整数としての解析を試み、指定された基数で有効な数字ではなくなるまで解析を続けます。文字列が有効な数字ではじまらない場合、`0`が返されます。 + +デフォルトでは10進数として解析されますが、他の基数(`2`から`36`まで)をパラメータで指定することができます。 + +`A`は10進数の一部として有効でないため`"42A7".to_i`は`42`を返しますが、`"42A7".to_i(16)`は16進数`0x42A7`の値(10進数では`17063`)を返すことに注意してください。 + +--------------------------------------------------------------------------- + +**A28. (b)** + +`has_key?`、`include?`、`key?`、`member?`はすべて同じメソッドの別名で、与えられたキーがハッシュに存在する場合`true`を、存在しない場合`false`を返します。 + +`Hash`に`contain?`メソッドはありません。 + +--------------------------------------------------------------------------- + +**A29: (a)および(e)** + +配列の操作に関する注意事項です。 + +- `reject!`に加えて`reject`もあり、元の配列を変更する代りに新しい配列を返します。 +- `delete_if`の非破壊的バージョンはないため、`delete_if!`というメソッドはありません。Rubyでは似た機能のうち片方がより危険である場合にだけメソッド名の末尾に`!`を付けます。 +- `Array#slice`は`Array#[]`の別名で、条件によるフィルタリングを行うのではなく、インデックスにより特定の要素や部分配列を返します。`Array#slice`はブロックを取りません。 + +--------------------------------------------------------------------------- + +**A30: (c)** + +`|`演算子は和集合に相当します。二つの配列を重複を除去して結合し、元の順序を保持した新しい配列を返します。 + +--------------------------------------------------------------------------- + +**A31: (d)** + +`%i(...)`は式展開を行わずにシンボルの配列を返します。シンボルは空白で区切られます。 + +詳細は[%記法のドキュメント](https://docs.ruby-lang.org/ja/3.1/doc/spec=2fliteral.html#percent)を参照してください。 + +--------------------------------------------------------------------------- + +**A32: (b)** + +`begin/rescue/end`では最初に該当した`rescue`節が実行されます。 + +`SomeOtherError`は`SomeError`のサブクラスなので、`rescue SomeError`節が該当して実行されます。 + +現実のアプリケーションでは、一般的なエラーよりも特定的なエラーから順に`rescue`するのがよい習慣です(例えば、`rescue StandardError`は最後に記述します)。 + +--------------------------------------------------------------------------- + +**A33: (c)** + +0による除算で`ZeroDivisionError`が発生します。 + +`ZeroDivisionError`が補足され、メッセージが出力されます。`exit(1)`はエラーコードとともにプログラムの実行を終了します。 + +しかし、`begin...end`に`ensure`節があるため、インタープリタの終了前に`ensure`節が実行されます。 + +`ensure`節は、例外が発生したりRubyが終了した時にも後始末を行うことができるため、便利です。ファイルハンドルやデータベース接続のクローズなどに利用されます。 + +--------------------------------------------------------------------------- + +**A34: (e)** + +デフォルトでは、明示的にスーパークラスを指定してもしなくても、すべてのクラスは`Object`を継承します。 + +`Object`を継承しないクラス階層を構築するには、代りに`BasicObject`を継承することができます。`BasicObject`は非常に少ない機能しか備えておらず、通常のユースケースでは`BasicObject`を直接継承する必要はありません。 + +--------------------------------------------------------------------------- + +**A35: (c)** + +クラス定義はいつでも再オープンして更新することができます。`Object`のような組み込みクラスの場合も同様です。 + +すべての組み込みクラス(ただし`BasicObject`は除く)は`Object`を継承しているため、`Object`にメソッドを追加するとすべてのオブジェクトで利用できます。 + +--------------------------------------------------------------------------- + +**A36: (c)** + +クラスに対して`new`メソッドが呼ばれると、そのクラスのインスタンスが生成され、そのインスタンスに対して`initialize`が呼ばれます。この動作によりインスタンス生成時の初期化が可能になっています。 + +--------------------------------------------------------------------------- + +**A37: (d)** + +`Class`に定義されている`new`メソッドは新しいインスタンスの作成に使用されます。 + +--------------------------------------------------------------------------- + +**A38: (a)** + +予約語`super`は継承ツリーの祖先の同名のメソッドを呼びます。 + +この例では、`Bar.new`によって`Bar#initialize`が呼ばれ、`@var = "banana"`の代入が実行されます。しかしその直後に`super`によって`Foo#initialize`が呼ばれて`@var = apple"`の代入が実行されるため、最終的に`apple`が出力されます。 + +--------------------------------------------------------------------------- + +**A39: (d)** + +[String#delete_prefix](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_DELETE_PREFIX)は与えられた文字列を先頭から削除した文字列を返します。 + +[String#delete](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_DELETE)は引数で指定されたすべての文字を削除するため、`"$foo$".delete("$")`の評価結果は`"foo"`になります。 + + +[String#sub](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_SUB)は2つの引数を取り、[String#chop](https://docs.ruby-lang.org/ja/3.1/class/String.html#I_CHOP)は引数を取らないため、`sub("$")`と`chop("$")`はArgumentErrorになります。 + +--------------------------------------------------------------------------- + +**A40: (c)** + +`to_a`という名前のメソッドは慣習的にオブジェクトを配列に変換するために使用され、Rubyのコレクションクラスで利用可能です。 + +いくつかのオブジェクトでは`to_ary`も実装され、暗黙的な配列への変換に使用されます。例えば、`Array#flatten`はそれぞれの要素に対して`to_ary`の呼び出しを試みます。しかし、通常のユースケースでは`to_ary`はあまり使用されません。 + +--------------------------------------------------------------------------- + +**A41: (b)** + +`#find`メソッドは`Enumerable`モジュールに定義されており、ブロックの値が真になる最初の要素を返します。 + +`Enumerable#find`には`Enumerable#detect`という別名があることに注意してください。 + +--------------------------------------------------------------------------- + +**A42: (a)および(c)** + +`sort_by`メソッドはコレクションの要素に対してブロックの値を対応付け、ブロックの値の昇順で要素をソートします。 + +`sort`メソッドは(ブロックがない場合)要素を昇順にソートします。ブロックを与えると要素をブロックで比較してソートすることができます。 + +`sort_by`も`sort`もオブジェクトを`<=>`演算子で比較できることに依存しています。Rubyの数値クラスはすべて`<=>`演算子を実装していますが、自分は作成したクラスに定義することもできます。 + +--------------------------------------------------------------------------- + +**A43: (b)** + +`sort`メソッドにブロックを与えると、要素をブロックで比較してソートします。 + +ブロックでは二つの要素の比較を行い、最初の要素の順序が前の場合は負の値を、二つの要素の順序が同じ場合は0を、最初の要素の順序が後の場合は正の値を返す必要があります。 + +Rubyの数値クラスの`<=>`の動作は、この挙動を自動的に提供します。 + +``` +>> 3 <=> 1 +=> 1 +>> 3 <=> 3 +=> 0 +>> 3 <=> 5 +=> -1 +``` + +`<=>`(UFO演算子)は意味のあるソート順序をもつ任意のオブジェクトに実装可能です。 + +--------------------------------------------------------------------------- + +**A44: (b)** + +The `seek` method is used to move to a specific byte offset in an I/O stream. +Offsets are zero-based, so `seek(5)` sets the position in the stream to just *after* the fifth byte. +`seek`メソッドはI/Oストリームの特定のバイトオフセットに移動するために使用されます。 +オフセットは0ベースで、`seek(5)`は5バイト目の直後の位置にセットします。 + +`gets`メソッドはストリームの現在の位置から行の終端まで読み込みます。 + +--------------------------------------------------------------------------- + +**A45: (a)** + +`"r"`オープンモードは「ファイルの先頭から読み込みのみ」を意味します。 + +これはデフォルトの挙動として安全で、もっとも一般的なユースケースです。 + +--------------------------------------------------------------------------- + +**A46: (d)および(e)** + +Rubyでは以下のI/Oオープンモードがサポ一トされています。 + +``` +"r" ファイルの先頭から読み込みのみ(デフォルトのモード) + +"r+" ファイルの先頭から読み書き可能 + +"w" 既存のファイルを0バイトに切り詰めるか新しくファイルを作成し、書き込みのみ + +"w+" 既存のファイルを0バイトに切り詰めるか新しくファイルを作成し、読み書き可能 + +"a" 存在しなければ新しくファイルを作成し、ファイル末尾に追記。書き込みのみ + +"a+" 存在しなければ新しくファイルを作成し、ファイル末尾に追記。読み書き可能 +``` + +--------------------------------------------------------------------------- + +**A47: (b)および(c)** + +補足説明: + +fileutils標準ライブラリの`FileUtils.mv`はディレクトリの名前変更に使用できます。 + +`File.basename`はパスの末尾のファイル名を取得するのに使用されます(例: `File.basename("long/path/to/something") #=> "something"`)。 + +--------------------------------------------------------------------------- + +**A48:** (b) + +部分配列のインデックスの指定方法(Q25)と同様に、開始位置と長さを指定して部分文字列を取得することができます。 + +インデックスはバイト単位ではなく文字(コードポイント)単位であることに注意してください。 + +--------------------------------------------------------------------------- + +**A49: (b)** + +置換文字列の長さは元の部分文字列の長さと同じでなくともよいことに注意してください。例えば以下のような操作が可能です。 + +``` +>> str = "boat" +=> "boat" +>> str[1,2] = "uil" +=> "uil" +>> str +=> "built" +``` + +--------------------------------------------------------------------------- + +**A50: (b)** + +Rubyの数値クラスでは算術演算の時にオブジェクトを同じ型に変換する`coerce`メソッドが定義されています。このメソッドは`String`クラスでは定義されていないため、`TypeError`が発生します。 + +`"hi" * 5`のように順番を入れ替えた場合、結果は`"hihihihihi"`になることに注意してください。これは`String`自体に`*`演算子が定義されていて、文字列が左辺の場合に使用されるためです。 + +--------------------------------------------------------------------------- + diff --git a/silver_ja.md b/silver_ja.md new file mode 100644 index 0000000..69c4ad7 --- /dev/null +++ b/silver_ja.md @@ -0,0 +1,977 @@ +# Ruby技術者認定試験Silver模擬問題 + +[回答](silver_answers_ja.md) + +**Q1. Rubyにおける真の値として正しいものをすべて選んでください。(2つ選択)** + +- (a) `""` +- (b) `0` +- (c) `false` +- (d) `nil` + +------------------------------------------------------------------------- + +**Q2. Rubyの予約語として正しいものをすべて選んでください。(2つ選択)** + +- (a) `each` +- (b) `rand` +- (c) `class` +- (d) `send` +- (e) `true` + +--------------------------------------------------------------------------- + +**Q3. Rubyの変数名として正しいものを選んでください。(1つ選択)** + +- (a) `3y` +- (b) `false` +- (c) `_9class` +- (e) `xyz$` + +--------------------------------------------------------------------------- + +**Q4. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(2つ選択)** + +``` +$code = "CODE" +__(1)__ + +[出力] +i like writing CODE +``` + +- (a) `puts "i like writing #{$code}"` +- (b) `puts "i like writing #$code"` +- (c) `puts 'i like writing #{$code}'` +- (d) `puts 'i like writing #$code'` + +--------------------------------------------------------------------------- + +**Q5. 以下のコードがあります。** + +``` +num = 025 +puts num +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) `nil` +- (b) `025` +- (c) `21` +- (d) `25` + +--------------------------------------------------------------------------- + +**Q6. 以下のコードがあります。** + +``` +x = "Hello" +y = x.empty? ? 1 : 2 +p y +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) 1 +- (b) 2 +- (c) "Hello" +- (d) true + +--------------------------------------------------------------------------- + +**Q7. 以下のコードがあります。** + +``` +amount = 120 + +size = case amount + when 1..120; "S" + when 120..170; "M" + when 170..200; "L" + else "XL" +end + +p size +``` + +- (a) `"S"` +- (b) `"M"` +- (c) `"L"` +- (d) `"XL"` + +**実行結果として正しいものを選択してください。(1つ選択)** + +--------------------------------------------------------------------------- + +**Q8. 以下のコードがあります。** + +``` +item = "apple" + +["banana", "carrot", "daikon"].each do |item| + puts item +end + +puts item +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*(a)* +文法エラーが発生する + +*(b)* +例外が発生する + +*(c)* +``` +banana +carrot +daikon +daikon +``` + +*(d)* +``` +banana +carrot +daikon +apple +``` + +--------------------------------------------------------------------------- + +**Q9. 以下のコードがあります。** + +``` +x = 0 + +4.times do |i| + x += i +end + +p x +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + + +- (a) `0` +- (b) `4` +- (c) `6` +- (d) 文法エラーが発生する + +--------------------------------------------------------------------------- + +**Q10. 以下のコードがあります。** + +``` +s = "abcde" +p s.each_char.map { |i| + i * 2 +} +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) `[97, 98, 99, 100, 101]` +- (b) `[194, 196, 198, 200, 202]` +- (c) `["a", "b", "c", "d", "e"]` +- (d) `["aa", "bb", "cc", "dd", "ee"]` +- (e) 実行時にエラーになる + +--------------------------------------------------------------------------- + +**Q11. 以下のコードがあります。** + +``` +p "cocoa".chars.tally +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) `{99=>2, 111=>2, 97=>1}` +- (b) `{?c=>2, ?o=>2, ?a=>1}` +- (c) `{"c"=>2, "o"=>2, "a"=>1}` +- (d) 実行時にエラーになる + +--------------------------------------------------------------------------- + +**Q12. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(1つ選択)** + +``` +puts "blah blah blah".__(1)__(/blah/, "yay") + +[出力] +yay yay yay +``` + +- (a) `sub` +- (b) `gsub` +- (c) `replace` +- (d) `replace_all` + +--------------------------------------------------------------------------- + +**Q13. 以下のコードがあります。** + +``` +s = "pear" + +if s.empty? + puts "blank" +elsif s.length < 5 + puts "short" +else + puts "long" +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) blank +- (b) short +- (c) long +- (d) 例外が発生する + +--------------------------------------------------------------------------- + +**Q14: 以下のコードがあります。** + +``` +["foo: abc", "bar: 100"].each do |i| + p i.slice(/[0-9]+/)&.to_i +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*(a)* +``` +0 +100 +``` + +*(b)* +``` +nil +100 +``` + +*(c)* +``` +false +100 +``` + +*(d)* +文法エラーが発生する + +*(e)* +実行時にエラーになる + +--------------------------------------------------------------------------- + +**Q15: 以下のコードがあります。** + +``` +def foo(x: 1, y: 2, z: 3) + p [x, y, z] +end + +foo(y: 4, z: 5) +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) `[1, 2, 3]` +- (b) `[1, 4, 5]` +- (c) 文法エラーが発生する +- (d) 実行時にエラーになる + +--------------------------------------------------------------------------- + +**Q16: 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(1つ選択)** + +``` +def foo(x:, y:, z:) + p [x, y, z] +end + +h = {x: 1, y: 2, z: 3} +__(1)__ +[出力] +[1, 2, 3] +``` + +- (a) `foo(*h)` +- (b) `foo(**h)` +- (c) `foo(&h)` +- (d) `foo(^h)` + +--------------------------------------------------------------------------- + +**Q17. "Ruby"または"ruby"のいずれかの文字列のみにマッチする正規表現をすべて選択してください。(2つ選択)** + +- (a) `/\A[Rr]uby\z/` +- (b) `/\ARuby|ruby\z/` +- (c) `/\A[Rr][u][b][y]\z/` +- (d) `/\AR|ruby\z/` + +--------------------------------------------------------------------------- + +**Q18.以下のコードがあります。** + +``` +MSG = 42 +MSG += 5 +p MSG +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) 警告なしで`47`が表示される。 +- (b) MSGは定数なのでエラーが発生する。 +- (c) MSGは定数なので`42`が表示される。 +- (d) MSGは定数なので警告が表示されるが、`47`が表示される。 + +--------------------------------------------------------------------------- + +**Q19. 以下のコードがあります。** + +``` +MSG = "hello" +MSG.upcase! +p MSG +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) MSGは定数なのでエラーが発生する。 +- (b) 警告なしで`HELLO`が表示される。 +- (c) MSGは定数なので警告が表示されるが、`HELLO`が表示される。 +- (d) MSGは定数なので`hello`が表示される。 + +--------------------------------------------------------------------------- + +**Q20. 以下の説明のうち正しいものをすべて選択してください。(2つ選択)** + +- (a) ローカル変数は小文字ではじまり、2文字以上の長さである。 +- (b) グローバル変数は$ではじまる。 +- (c) インスタンス変数は*ではじまる。 +- (d) クラス変数は$ではじまる。 +- (e) 定数は大文字ではじまる。 + +--------------------------------------------------------------------------- + +**Q21. 以下のコードがあります。** + +``` +x = [1,2,3,4,5,6,7,8] +y = x +x.reject! { |e| e.even? } +p x +p y +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + + +*(a)* +``` +[1, 3, 5, 7] +[1, 2, 3, 4, 5, 6, 7, 8] +``` + +*(b)* +``` +[1, 2, 3, 4, 5, 6, 7, 8] +[1, 2, 3, 4, 5, 6, 7, 8] +``` + +*(c)* +``` +[1, 3, 5, 7] +[1, 3, 5, 7] +``` + +*(d)* +``` +[1, 3, 5, 7] +[2, 4, 6, 8] +``` + +--------------------------------------------------------------------------- + +**Q22. 以下のコードがあります。** + +``` +a = [ 2, 4, 6, 8, 10 ] +a.shift +a.pop +a.push(12) +p a +``` + +- (a) `[2, 4, 6, 8, 10, 12]` +- (b) `[2, 4, 6, 8, 10]` +- (c) `[4, 6, 8, 12]` +- (d) `[4, 6, 8]` + +**実行結果として正しいものを選択してください。(1つ選択)** + +--------------------------------------------------------------------------- + +**Q23. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(1つ選択)** + +``` +x = true +x __(1)__ exit(1) +puts("succeeded!") + +[出力] +succeeded! +``` + + +- (a) `|` +- (b) `||` +- (c) `&` +- (d) `&&` + +--------------------------------------------------------------------------- + +**Q24. 以下のコードがあります。** + +``` +m = true +m or n = true +p n +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + + +- (a) `true` +- (b) `false` +- (c) `nil` +- (d) 文法エラーが発生する + +--------------------------------------------------------------------------- + +**Q25. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(2つ選択)** + +``` +x = [ 9, 7, 5, 3, 1 ] +p __(1)__ + +[出力] +[7, 5, 3] +``` + +- (a) `x[1, 3]` +- (b) `x[1..-1]` +- (c) `x[-3..-1]` +- (d) `x[-4..-2]` + +--------------------------------------------------------------------------- + +**Q26. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(2つ選択)** + +``` +ary = [ 1, 2, 3, 4, 5 ] +p ary.__(1)__ { |i| i.odd? } + +[出力] +[1, 3, 5] +``` + +- (a) `collect` +- (b) `select` +- (c) `map` +- (d) `filter` +- (e) `filter_map` + +--------------------------------------------------------------------------- + +**Q27. 以下のコードがあります。** + +``` +puts "42A7".to_i +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) 42 +- (b) 42A7 +- (c) 17063 +- (d) 実行時にエラーになる + +--------------------------------------------------------------------------- + +**Q28. 次のメソッドのうち`:c`がハッシュのキーとして存在するかどうかを「返さない」ものを選択してください。(1つ選択)** + +``` +h = {a: 2, b: 4, c: 6, d: 8, e: 10} +``` + +- (a) `p h.has_key?(:c)` +- (b) `p h.contain?(:c)` +- (c) `p h.include?(:c)` +- (d) `p h.key?(:c)` +- (e) `p h.member?(:c)` + +--------------------------------------------------------------------------- + +**Q29. "以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(2つ選択)** + +``` +a = [120, 40, 20, 80, 160, 60, 180] +a.__(1)__ +p a + +[出力] +[120, 80, 160, 180] +``` + +- (a) `reject! {|i| i < 80}` +- (b) `slice {|i| i < 80 }` +- (c) `slice! {|i| i < 80}` +- (d) `delete_if! {|i| i < 80}` +- (e) `delete_if {|i| i < 80}` +- (f) `reject {|i| i < 80}` + +--------------------------------------------------------------------------- + +**Q30. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(1つ選択)** + +``` +p ["apple", "banana"] __(1)__ ["banana", "carrot"] + +[出力] +["apple", "banana", "carrot"] +``` + +- (a) `.concat` +- (b) `&` +- (c) `|` +- (d) `||` + + +--------------------------------------------------------------------------- + +**Q31. 以下のコードがあります。** + +``` +p %i(x1 x2 x3) +``` + +実行結果として正しいものを選択してください。(1つ選択) + +- (a) `"x1 x2 x3"` +- (b) `[1, 2, 3]` +- (c) `["x1", "x2", "x3"]` +- (d) `[:x1, :x2, :x3]` + +--------------------------------------------------------------------------- + +**Q32. 以下のコードがあります。** + +``` +class SomeError < StandardError; end +class SomeOtherError < SomeError; end + +def meth1 + raise SomeOtherError.new("error") +end + +begin + meth1 +rescue SomeError + print "SomeError" +rescue SomeOtherError + print "SomeOtherError" +end +``` + +実行結果として正しいものを選択してください。(1つ選択) + +- (a) A syntax error +- (b) `SomeError` +- (c) `SomeErrorSomeOtherError` +- (d) `SomeOtherError` + +--------------------------------------------------------------------------- + +**Q33. 以下のコードがあります。** + +``` +begin + ans = 100/0 + puts ans +rescue ZeroDivisionError + puts "Error: ZeroDivisionError" + exit 1 +ensure + puts "DONE!" +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +*(a)* +``` +0 +DONE! +``` + +*(b)* + +``` +Error: ZeroDivisionError +``` + +*(c)* +``` +Error: ZeroDivisionError +DONE! +``` + +*(d)* +``` +Error: ZeroDivisionError +0 +``` + +--------------------------------------------------------------------------- + +**Q34. Rubyのクラスの説明として正しいものを選択してください。(1つ選択)** + +クラスのスーパークラスを明示的に指定しなかった場合、 + +- (a) 例外`UndefinedParentClassError`が発生する +- (b) 文法エラーが発生する +- (c) `Module`クラスがスーパークラスになる +- (d) スーパークラスのないクラスが作成される +- (e) `Object`クラスがスーパークラスになる + +--------------------------------------------------------------------------- + +**Q35. 以下のコードがあります。** + +``` +class Object + def moo + puts "MOO!" + end +end + +"Cow".moo +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) 何も出力されない +- (b) 実行時にエラーになる +- (c) `MOO!` +- (d) `nil` + +--------------------------------------------------------------------------- + +**Q36. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(1つ選択)** + +``` +class Shouter + def __(1)__(message) + @message = message + end + + def greet + puts @message.upcase + end +end + +g = Shouter.new("Hello, world!") +g.greet + +[出力] +HELLO, WORLD! +``` + +- (a) `Shouter` +- (b) `new` +- (c) `initialize` +- (d) `__init__` + +--------------------------------------------------------------------------- + +**Q37. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(1つ選択)** + +``` +class Shouter + def initialize(message) + @message = message + end + + def greet + puts @message.upcase + end +end + +g = __(1)__("Hello, world!") +g.greet + +[出力] +HELLO, WORLD! +``` + +- (a) `Shouter` +- (b) `#Shouter` +- (c) `new Shouter` +- (d) `Shouter.new` + +--------------------------------------------------------------------------- + +**Q38. 以下のコードがあります。** + +``` +class Foo + attr_reader :var + def initialize + @var = "apple" + end +end + +class Bar < Foo + def initialize + @var = "banana" + super + end +end + +bar = Bar.new +puts bar.var +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + + +- (a) apple +- (b) banana +- (c) 何も出力されない +- (d) 実行時にエラーになる + +--------------------------------------------------------------------------- + +**Q39. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(2つ選択)** + +``` +puts "$foo$".__(1)__("$") + +[出力] +foo$ +``` + +- (a) `sub` +- (b) `chop` +- (c) `delete` +- (d) `delete_prefix` + +--------------------------------------------------------------------------- + +**Q40. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(1つ選択)** + +``` +r = "a".."e" +p r.__(1)__ + +[出力] +["a", "b", "c", "d", "e"] +``` + +- (a) `array` +- (b) `to_ary` +- (c) `to_a` +- (d) `to_array` + +--------------------------------------------------------------------------- + +**Q41. 以下のコードがあります。** + +``` +p [0,1,2,3,4,5].find {|x| x < 3} +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) `[0, 1, 2]` +- (b) `0` +- (c) `[0, 1, 2, 3]` +- (d) `true` + +--------------------------------------------------------------------------- + +**Q42. 以下の実行結果を出力するコードがあります。 +__(1)__に入る適切な記述を選択してください。(2つ選択)** + +``` +p [1,16,8,4,2].__(1)__ + +[出力] +[16, 8, 4, 2, 1] +``` + + +- (a) `sort_by { |x| -x }` +- (b) `sort_reverse` +- (c) `sort.reverse` +- (d) `reverse.sort` + +--------------------------------------------------------------------------- + +**Q43. 配列を降順にソートするコードがあります。 +__(1)__に入る適切な記述を選択してください。(2つ選択)** + +``` +ary = [2,4,8,1,16] +p ary.__(1)__ + +[出力] +[16, 8, 4, 2, 1] +``` + +- (a) `sort { |i,j| -i <= -j }` +- (b) `sort { |i,j| -i <=> -j }` +- (c) `sort { |i,j| i >= j }` +- (d) `sort{ |i,j| i <=> j }` + +--------------------------------------------------------------------------- + +**Q44. 以下のコードがあります。** + +``` +File.write("test", "hellorubyworld\n") +File.open("test") do |file| + file.seek(5) + print file.gets +end +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) hello +- (b) rubyworld +- (c) hellor +- (d) rubyw +- (e) orubyworld + +--------------------------------------------------------------------------- + +**Q45. 以下のコードではopenメソッドの第2引数を省略してファイルを開いています。このケースで暗黙的に第2引数として指定されるものを選択してください。** + +``` +file = open("sample.txt") +``` + +- (a) `r` +- (b) `r+` +- (c) `a` +- (d) `a+` +- (e) `w` +- (f) `w+` + +--------------------------------------------------------------------------- + +**Q46: test_one.txtの内容をtest_two.txtにコピーするコードがあります。 +__(1)__に入る適切な記述を選択してください。** + +**test_two.txtがすでに存在する場合、このコードは最初にファイルサイズを0にし、先頭から内容を上書きするものとします。(2つ選択)** + +``` +open("test_one.txt") {|source| + open("test_two.txt", "__(1)__") {|dest| + dest.write(source.read) + } +} +``` + +- (a) `r+` +- (b) `a` +- (c) `a+` +- (d) `w` +- (e) `w+` + +--------------------------------------------------------------------------- + +**Q47: `Dir`クラスに存在しないクラスメソッドを選択してください。(2つ選択)** + +- (a) `Dir.pwd` +- (b) `Dir.rename` +- (c) `Dir.basename` +- (d) `Dir.chdir` +- (e) `Dir.delete` + +--------------------------------------------------------------------------- + +**Q48. 以下のコードがあります。** + +``` +p "hello ruby world"[6,4] +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) `"hello "` +- (b) `"ruby"` +- (c) `" world"` +- (d) 実行時にエラーになる + +--------------------------------------------------------------------------- + +**Q49:** + +以下のコードがあります。 + +``` +str = "bat" +str[1,1] = "o" +p str +``` + +実行結果として正しいものを選択してください。(1つ選択) + +- (a) `"boo"` +- (b) `"bot"` +- (c) `"oat"` +- (d) `"o"` + +--------------------------------------------------------------------------- + +**Q50. 以下のコードがあります。** + +``` +puts 5 * "hi" +``` + +**実行結果として正しいものを選択してください。(1つ選択)** + +- (a) `"hihihihihi"` +- (b) 実行時にエラーになる +- (c) `"5hi"` +- (d) `"5*hi"` + +--------------------------------------------------------------------------- + From dccfa77b6d3e409b7d818f4396fecf194f4b5839 Mon Sep 17 00:00:00 2001 From: Shugo Maeda Date: Fri, 30 Sep 2022 14:34:52 +0900 Subject: [PATCH 2/7] Add version --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6da783c..1bcab05 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Ruby Association Certified Ruby Programmer Examination -Sample questions for [Ruby Association Certified Ruby Programmer Examination](https://www.ruby.or.jp/en/certification/examination/) +Sample questions for [Ruby Association Certified Ruby Programmer Examination version 3](https://www.ruby.or.jp/en/certification/examination/) * [Sample Questions for Silver](silver.md) ([Japanese](silver_ja.md)) * [Sample Questions for Gold](gold.md) ([Japanese](gold_ja.md)) From b02f7f4fa3ab3016c8079333fd7c75d7057ec451 Mon Sep 17 00:00:00 2001 From: Yuki Horikoshi <59280290+yuki-snow1823@users.noreply.github.com> Date: Sat, 4 Nov 2023 22:54:07 +0900 Subject: [PATCH 3/7] [delete]English description --- gold_answers_ja.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/gold_answers_ja.md b/gold_answers_ja.md index 35815ad..c13c61c 100644 --- a/gold_answers_ja.md +++ b/gold_answers_ja.md @@ -287,8 +287,6 @@ ScriptError < Exception **A37:** (B) -In class methods, `self` refers to an instance of the `Class` object. -In instance methods, `self` refers to whatever the currently instantiated object is. クラスメソッドでは、`self`は`Class`インスタンスを参照します。 インスタンスメソッドでは、`self`は現在インスタンス化されているオブジェクトを参照します。 From 8f6d450e5a1eca90d6dcb2a9bbc1e4f041f29471 Mon Sep 17 00:00:00 2001 From: universato Date: Wed, 5 Oct 2022 14:27:05 +0900 Subject: [PATCH 4/7] Fix typo in silver Q39 & Q43 (version3) --- silver.md | 3 +-- silver_ja.md | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/silver.md b/silver.md index 975c407..7e027ca 100644 --- a/silver.md +++ b/silver.md @@ -764,7 +764,7 @@ puts bar.var --------------------------------------------------------------------------- -**Q39. Which of the following can be inserted into `__(1)__` in order for the given code to generate the output below? (Choose two.)** +**Q39. Which of the following can be inserted into `__(1)__` in order for the given code to generate the output below? (Choose one.)** ``` puts "$foo$".__(1)__("$") @@ -959,4 +959,3 @@ puts 5 * "hi" - (d) `"5*hi"` --------------------------------------------------------------------------- - diff --git a/silver_ja.md b/silver_ja.md index 69c4ad7..f382d22 100644 --- a/silver_ja.md +++ b/silver_ja.md @@ -775,7 +775,7 @@ puts bar.var --------------------------------------------------------------------------- **Q39. 以下の実行結果を出力するコードがあります。 -__(1)__に入る適切な記述を選択してください。(2つ選択)** +__(1)__に入る適切な記述を選択してください。(1つ選択)** ``` puts "$foo$".__(1)__("$") @@ -843,7 +843,7 @@ p [1,16,8,4,2].__(1)__ --------------------------------------------------------------------------- **Q43. 配列を降順にソートするコードがあります。 -__(1)__に入る適切な記述を選択してください。(2つ選択)** +__(1)__に入る適切な記述を選択してください。(1つ選択)** ``` ary = [2,4,8,1,16] From 23598c14d0a9848ad5c311e5df5bed584feb2cb6 Mon Sep 17 00:00:00 2001 From: Shugo Maeda Date: Fri, 21 Jun 2024 14:29:48 +0900 Subject: [PATCH 5/7] Fix for `**` introduced in Ruby 3.2 --- gold.md | 2 +- gold_ja.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gold.md b/gold.md index cb45dff..38dfe9a 100644 --- a/gold.md +++ b/gold.md @@ -155,7 +155,7 @@ p round(2.5, half: :even) *A:* `*` -*B:* `**` +*B:* `&` *C:* `..` diff --git a/gold_ja.md b/gold_ja.md index 6364923..a7a87b8 100644 --- a/gold_ja.md +++ b/gold_ja.md @@ -155,7 +155,7 @@ p round(2.5, half: :even) *A:* `*` -*B:* `**` +*B:* `&` *C:* `..` From 477612350a67d1dcf522c154631f0baf02357035 Mon Sep 17 00:00:00 2001 From: Shugo Maeda Date: Thu, 25 Jul 2024 09:50:37 +0900 Subject: [PATCH 6/7] `it` will be introduced in Ruby 3.4 --- gold.md | 2 +- gold_ja.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gold.md b/gold.md index 38dfe9a..cb6b8f0 100644 --- a/gold.md +++ b/gold.md @@ -763,7 +763,7 @@ p ["foo", "bar", "baz"].map { __(1)__.upcase } *C:* `$_` -*D:* `it` +*D:* `@1` ----------------------------------------------------------------- diff --git a/gold_ja.md b/gold_ja.md index a7a87b8..23b2ed2 100644 --- a/gold_ja.md +++ b/gold_ja.md @@ -763,7 +763,7 @@ p ["foo", "bar", "baz"].map { __(1)__.upcase } *C:* `$_` -*D:* `it` +*D:* `@1` ----------------------------------------------------------------- From 0742172ffb82b22a9be9ef8c682f87e81ffda861 Mon Sep 17 00:00:00 2001 From: Shugo Maeda Date: Wed, 11 Dec 2024 10:21:22 +0900 Subject: [PATCH 7/7] The "shadowing outer local variable" warning was removed from Ruby --- silver_answers.md | 2 +- silver_answers_ja.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/silver_answers.md b/silver_answers.md index bb74a5f..59960ae 100644 --- a/silver_answers.md +++ b/silver_answers.md @@ -62,7 +62,7 @@ So although both `1..120` and `120..170` include `120`, the `when 1..120` branch Although local variables from the surrounding scope are accessible within blocks, block parameters themselves are always block-local variables. This means that when a block parameter has the same name as a local variable from the surrounding scope, within the block any references will refer to the block-local variable. This prevents accidental modification of variables from the outside scope due to naming collisions. -Defining block parameters with the same name as a local variable from the surrounding scope is considered an antipattern and may be a sign of an accidental programming error. To catch this problem, run `ruby` with the `-w` flag, and you will see warnings like `warning: shadowing outer local variable - item` wherever this problem occurs. +Defining block parameters with the same name as a local variable from the surrounding scope is considered an antipattern and may be a sign of an accidental programming error. To catch this problem, use [Lint/ShadowingOuterLocalVariable](https://docs.rubocop.org/rubocop/cops_lint.html#lintshadowingouterlocalvariable) of [RuboCop](https://rubocop.org/). --------------------------------------------------------------------------- diff --git a/silver_answers_ja.md b/silver_answers_ja.md index 500378e..4695d6a 100644 --- a/silver_answers_ja.md +++ b/silver_answers_ja.md @@ -60,7 +60,7 @@ Rubyの範囲リテラル`x..y`は、`y`の値を含みます。 ブロックでは外側のスコープのローカル変数にアクセスすることができますが、ブロックパラメータ自体は常にブロックローカルです。これはブロックパラメータの名前が外側のローカル変数と同じ場合、ブロック内ではブロックローカル変数が参照されることを意味します。これによって、変数名が衝突した場合に外側のローカル変数を誤って変更することが防がれます。 -外側のローカル変数と同名のブロックパラメータを定義することはアンチパターンと考えられ、プログラムの間違いのサインかもしれません。この問題を発見するには、`ruby`を`-w`オプション付きで実行し、`warning: shadowing outer local variable - item`のような警告を表示させるようにします。 +外側のローカル変数と同名のブロックパラメータを定義することはアンチパターンと考えられ、プログラムの間違いのサインかもしれません。この問題を発見するには、[RuboCop](https://rubocop.org/)の[Lint/ShadowingOuterLocalVariable](https://docs.rubocop.org/rubocop/cops_lint.html#lintshadowingouterlocalvariable)を使用します。 ---------------------------------------------------------------------------