简介的ruby代码

by 卡布卡布 at about 9 years ago, last updated at about 9 years ago
S

1.列表中每项乘2

p (1..10).map {|n| n * 2}

2.列表中数字求和

p (1...1000).inject  { |sum,n| sum + n}

3.检查字符串是否包括某个单词

words = ["hi", "hello", "perfect", "sum", "sup"]

example = "hello world i'm the super man "

p words.any? {|word| example.include? (word)}     #=>  sure

4.过滤数列

p [33, 44, 55, 66, 77, 88].partition {|n| n > 60 }  # =>  [[66, 77, 88], [33, 44, 55]]

5.生日快乐

2.times  {|n| puts "Happy Birthday #{n = 2 ? "dear cabda " : "to you"}"}