5.22

2965 ワード

1、unlessを使用して次のコードを1行に簡略化する
games = ["Super Mario Bros.", "Contra", "Metroid", "Mega Man 2"] if !games.empty? puts "Games in your vast collection: #{games.count}"end
解法:
puts "Games in your vast collection: #{games.count}" unless (games=["Super Mario Bros.", "Contra", "Metroid", "Mega Man 2"]).empty?

2、lambdaで以下のコードを書き換える
library = Library.new(GAMES) print_details = Proc.new do |game| puts "#{game.name} (#{game.system}) - #{game.year}"end library.exec_game('Contra', print_details)
解法:
library = Library.new(GAMES)
print_details = lambda do |game|
  puts "#{game.name} (#{game.system}) - #{game.year}"
end
library.exec_game('Contra', print_details)

3、yieldで以下のコードdef calculation(a,b,&block)block.call(a,b)endを書き換える
puts calculation(5, 5) { |a, b| a + b }
解法:
def calculation(a, b)
 yield(a, b)
end

puts calculation(5, 5) { |a, b| a + b }

4、以下のコードは何class C def hello@v 1=“var v 1 hello”puts@v 1 puts@@v 1 end@v 1=“var v 1”@@v 1=“var v 1 C”puts@v 1 end class D解法:C.new.hello
var v1 hello
var v1 D

C.new.v1
      
PS:           

C.v1
      
PS:               

5、superキーワードを使うときにsuperとsuper()を呼び出すのはどんな違いがありますか?
解法:
super     super ,               ,    ,  “  ”          
super()      

6、コードを書いて、2つの時間帯のすべての金曜日start_を出力します.date = '2017-01-01' end_date = '2017-05-01'
解法:
start_date = '2017-01-01' end_date = '2017-05-01'
def puts_Friday puts end
7、likesの作成方法、以下の要求を実現し、文字列配列を入力し、組み合わせた文字列likes[]//must be“no onelikes this”likes[“Peter”////must be“Peter likes this”likes[“Jacob”,“Alex”////////must be“Jacob and Alex like this”likes[“Max”,“John”,“Mark”////////must be“Max,John and Marklike this”likes[“Alex”,“Jacob”,“Mark”,“Mark”,“Mark”、"Max"]//must be "Alex, Jacob and 2 others like this"
string = "must be"
def likes puts "no one likes this"end
8、各単語の頭文字を大文字で入力する:「How can mirrors be real if our eyes aren't real」出力:「How Can Mirrors Be Real If Our Eyes Aren't Real」
解法:
"How can mirrors be real if our eyes aren't real".split.map(&:capitalize).join(' ')

9、入力した3つの数字が三角形def isTriangle(a,b,c)endを構成できるかどうかを判断する方法を書く
解法:
def isTrangle(a, b, c) if a + b > c && a - b < c puts "It is a trangle"end end
10、1つの方法を書いて、ただ循環を使うことを許可して、配列の逆順序を実現します[1,2,3]=>[3,2,1]
解法:
def bubble_sort a = [1,2,3]
f = 1 while f < a.length (0...(a.length-f)).each do |i| a[i], a[i+1] = a[i+1], a[i] if a[i] < a[i+1] end f += 1 end a end
PS: