5.22

1、使用unless简化以下代码到一行

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
@v1 = "var v1 hello"
puts @v1
puts @@v1
end
@v1 = "var v1"
@@v1 = "var v1 C"
puts @v1
end
class D < C
@@v1 = "var v1 D"
end
C.new.hello
C.new.v1
C.v1

解法:
C.new.hello

var v1 hello
var v1 D

C.new.v1

没有定义方法
PS:类方法不能使用实例变量

C.v1

没有定义方法
PS:不能引用一个未初始化的实例变量

5、在使用super关键字的时候 调用 super 和 super() 有什么区别?

解法:

super 当你使用super时,会发送一个消息给当前对象的父类,告诉父类,我的“兄弟”们要调用你的所有参数
super() 不调用参数

6、写一段代码,输出两个时间段时间所有的星期五
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 one likes 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 Mark like this"
likes ["Alex", "Jacob", "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, 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:

你可能感兴趣的:(5.22)