LoginSignup
2
0

More than 5 years have passed since last update.

Rubyクイズ

Last updated at Posted at 2016-12-07

自分が実際に業務でRubyを書いていてハマったところ、ハマりかけたところ、あるいは初心者がつまづきやすいところをクイズにしてみました。
皆さん、実行せずに答えられますか?

答えはこちら

クイズ1

Aの出力結果は何でしょう?

def hoge(options = {})
  foo = options.delete(:foo)
  puts "foo is #{foo}"
  puts "options is #{options}"
end

options = {foo: 'FOO', bar: 'BAR'}
hoge(options)
puts options #=> A

クイズ2

A, Bの出力結果は何でしょう?

INIT_STR = 'INIT STR:'

def hoge(num)
  temp = INIT_STR
  num.times do |n|
    temp << " #{n}"
  end
  temp
end

puts hoge(3) #=> A
puts hoge(3) #=> B

クイズ3

Aの出力結果は何でしょう?

def hoge(options = {}, foo: 'FOO')
  puts options
  puts foo
end

hoge(bar: 'bar', foo: 'foo') #=> A

クイズ4

A〜Hの実行結果は何でしょう?

Array(1)            # => A
Array(nil)          # => B
Array([])           # => C
Array.new           # => D
Array.new(1)        # => E
Array.new(nil)      # => F
Array.new(nil.to_i) # => G
Array.new([])       # => H

クイズ5

Aの実行結果は何でしょう?

class Hoge
  def foo
    self.bar
  end

private

  def bar
    puts 'bar'
  end
end

Hoge.new.foo # => A

クイズ6

Aの実行結果は何でしょう?

class Hoge
  attr_accessor :foo,

  def initialize(foo)
    @foo = foo
    puts @foo
  end
end

Hoge.new('bar') # => A

クイズ7

A, Bの実行結果は何でしょう?

def hoge
  sleep 1 # 重い処理
  'hoge'
end

if result1 = hoge
  puts result1 # => A
end
puts result2 if result2 = hoge # => B

思いついたら追加します。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0