Я подробно изучил документацию по ruby и в итоге составил шпаргалку (почти) всех методов для 3 наиболее часто используемых встроенных классов. Я обнаружил, что это один из самых полезных инструментов в процессе изучения рубина.
МАССИВЫ
(0..5).map { |i| i ** 2 } #=> [0, 1, 4, 9, 16, 25] (0..10).step(2).to_a #=> [0, 2, 4, 6, 8, 10] ("9".."12").to_a #=> ["9", "10", "11", "12"] (1..5).to_a #=> [1, 2, 3, 4, 5] (1...5).to_a #=> [1, 2, 3, 4] (1..6).partition {|v| v.even? } #=> [[2, 4, 6], [1, 3, 5]] (1..10).map { rand(10) } #=> [8, 6, 3, 9, 2, 1, 6, 2, 0, 7]
[3, 1, 2].sort #=> [1, 2, 3]
["1", "20", "300", "4"].sort_by { |i| i.length } #=> ["1", "4", "20", "300"]
["1", "20", "300", "4"].sort_by(&:length) #=> ["1", "4", "20", "300"]
[1, 2, 3, 4].map { |i| i * 2 } #=> [2, 4, 6, 8]
[[1,2],[3,4]].flat_map {|i| i } #=> [1, 2, 3, 4]
[1, 2, 3, 4].select { |i| i > 2 } #=> [3, 4]
[1, 2, 3, 4].detect { |i| i.between?(2, 3) } #=> 2
(1..10).find_all { |i| i % 3 == 0 } #=> [3, 6, 9]
(1..10).reject { |i| i % 3 == 0 } #=> [1, 2, 4, 5, 7, 8, 10]
(1..80).find_index {|i| i % 5 == 0 and i % 7 == 0} #=> 34
%w(albatross dog horse).max #=> "horse"
%w(albatross dog horse).max_by { |x| x.length } #=> "albatross"
%w(albatross dog horse).max_by(&:length) #=> "albatross"
# min is the same as max [1, 2, 3, 4].minmax #=> [1, 4]
%w(albatross dog horse).minmax_by(&:length) #=> ["dog", "albatross"]
[].none? #=> true [1, 2, 3].one? #=> false ["a"].one? #=> true
(1..100).grep 95..120 #=> [95, 96, 97, 98, 99, 100] IO.constants.grep(/SEEK/) #=> [:SEEK_SET, :SEEK_CUR, :SEEK_END] (1..6).group_by { |i| i % 3 } #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
[1, 2, 3].unshift 0 #=> [0, 1, 2, 3] [1, 2, 3] << 0 #=> [1, 2, 3, 0] [1, 2, 3].insert(2, "a") #=> [1, 2, "a", 3] [1, 2, 3].pop ==> 3 #=> [1, 2] [1, 2, 3].shift ==> 1 #=> [2, 3] [1, 2, 3, 4, 5, 6].take(3) #=> [1, 2, 3] [1, 2, 3, 4, 5, 6].drop(3) #=> [4, 5, 6] [1, 2, 3, 4, 5, 0].take_while { |i| i < 3 } #=> [1, 2] [1, 2, 3, 4, 5, 0].drop_while { |i| i < 3 } #=> [3, 4, 5, 0] ["a", "b", "c"].fetch(1) #=> "b" ["a", "b", "c"].index("b") #=> 1 [1, 2, 3, 4].delete_at(2) #=> [1, 2, 4] [1, 2, 3, 4].delete_if { |i| i % 2 == 0 } #=> [1, 3] [1, 2, 2, 3].delete(2) #=> [1, 3] [1, 2, 2, 3].uniq #=> [1, 2, 3]
[[1], 2, [3, [4]], 5, 6].flatten #=> [1, 2, 3, 4, 5, 6] [ 1, 2, [3, [4, 5]]].flatten(1) #=> [1, 2, 3, [4, 5]] *[1, 2, 3] #=> 1, 2, 3
[1, 2, 3, 3].count(3) #=> 2 [1, 2, 4, 2].count{|x| x % 2 == 0} #=> 3 [1, 2, 3] & [2, 3, 4] #=> [2, 3] # intersection [1, 2, 3] | [2, 3, 4] #=> [1, 2, 3, 4] # union [1, 2, 3] - [2, 3, 4] #=> [1] [1, 2, 3] + [2, 3, 4] #=> [1, 2, 3, 2, 3, 4]
[ "a", "b" ].concat ["c", "d"] #=> ["a", "b", "c", "d"]
# + creates a new array object, while concat mutates the original object
[1, 2, 3, 4][1..2] = ["a", "b"] #=> [1, "a", "b", 4]
[1, 2, 3].combination(1).to_a #=> [[1], [2], [3]] [1, 2, 3].combination(2).to_a #=> [[1,2], [1,3], [2,3]] [1, 2, 3].combination(3).to_a #=> [[1,2,3]] [1, 2, 3].combination(4).to_a #=> []
[1, 2, 3].permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] [1, 2, 3].permutation(1).to_a #=> [[1], [2], [3]] [1, 2, 3].permutation(2).to_a #=> [[1,2], [1,3], [2,1], [2,3], [3,1], [3,2]]
[1, 2, 3].product #=> [[1], [2], [3]] [1, 2, 3].product([4,5]) #=> [[1,4], [1,5], [2,4], [2,5], [3,4], [3,5]] [1, 2, 3].zip #=> [[1], [2], [3]] [1, 2, 3].zip([4,5]) #=> [[1, 4], [2, 5], [3, nil]] [1, 2].zip([3, 4, 5]) #=> [[1, 3], [2, 4]] [1, 2].zip([3, 4],[8]) #=> [[1, 3, 8], [2, 4, nil]]
["a", "b", "c"].cycle {|x| puts x } # a, b, c, a, b, c,.. forever.
["a", "b", "c"].cycle(2) {|x| puts x } # a, b, c, a, b, c.
[1, 2, 3].each { |i| print i + 5, " " } #=> "6 7 8"
[1, 2, 3].reverse_each {|x| print x, " " } #=> "3 2 1"
[1, 2, 3].reverse == [1, 2, 3].sort { |a, b| b <=> a } #=> [3, 2, 1]
(1..8).each_cons(3) {|a| print "#{a} "} #=> [1, 2, 3] [2, 3, 4] [3, 4, 5] [4, 5, 6] [5, 6, 7] [6, 7, 8]
(1..8).each_slice(3) {|a| print "#{a} " } #=> [1, 2, 3] [4, 5, 6] [7, 8]
[1, 2, 3, 4].rotate #=> [2, 3, 4, 1]
[[1,2], [3,4], [5,6]].transpose #=> [[1, 3, 5], [2, 4, 6]]
["a", "b", "c", "d", "e"].values_at(1, 3, 5) #=> ["b", "d", "e"]
[1, 2, 3, 4].inject(5) { |sum, n| sum + n } ==> 15 # 5 + sum of list
[1, 2, 3, 4].inject() { |sum, n| sum + n } ==> 10 # sum of list
[1, 2, 3, 4].inject(:+) #=> 10 # sum of list (1..n).inject(:*) #=> n! (1..n).reduce(:*) #=> n! # reduce == inject
(1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> nil (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> 35
ЕСЛИ ЕЩЕ
cats[i] == 0 ? cats[i] = 1 : cats[i] = 0
STRINGS
"cat o' 9 tails" =~ /\d/ #=> 7 (idx of number in str) "hello".rjust(20) #=> " hello" "hello".ljust(20) #=> "hello " "hello".center(20) #=> " hello " "hello".center(20, '-=-') #=> "-=--=--hello-=--=--=" " \tgoodbye\r\n ".strip #=> "goodbye" " hello ".lstrip #=> "hello "
"hello".tr('el', 'ip') #=> "hippo" "hello".tr('aeiou', '*') #=> "h*ll*" "hello".gsub(/[aeiou]/, '*') #=> "h*ll*" "hello".gsub(/([aeiou])/, '{\1}') #=> "h{e}ll{o}" "hello".gsub(/(?[aeiou])/, '{\k}') #=> "h{e}ll{o}" "hello".gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*" "hello".tr('eo', '3*') #=> "h3ll*"
"%-5s: something" % [ "ID" ] #=> "ID : something" "%5s: something" % [ "ID" ] #=> " ID: something" "foo = %{fax}" % { :fax => 'bar' } #=> "foo = bar"
"yellow moon".squeeze #=> "yelow mon" " now is the".squeeze(" ") #=> " now is the"
# inspect returns a string with a literal representation of the object nil.inspect == "nil" nil.to_s == "" p :symbol == puts :symbol.inspect #=> true puts "string" == print "string\n" #=> true
"-1234".hex #=> -4660 "0377bad".oct #=> 255 "11".to_i(2) #=> 3 "0a".to_i(16) #=> 10
"hello".index('e') #=> 1 "hello".index(?e) #=> 1 "abcd".insert(0, 'X') #=> "Xabcd"
"abcd".next #=> "abce" "THX1138".next #=> "THX1139"
"cruel world".chars #=> ["c", "r", "u", "e", "l", " ", "w", "o", "r", "l", "d"] "cruel world".scan(/\w+/) #=> ["cruel", "world"] "cruel world".scan(/.../) #=> ["cru", "el ", "wor"] "cruel world".scan(/(...)/) #=> [["cru"], ["el "], ["wor"]] "cruel world".scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]]
" now's the time".split #=> ["now's", "the", "time"] "hello".split(//) #=> ["h", "e", "l", "l", "o"] "hello you".split(//, 3) #=> ["h", "e", "llo you"]
"hello".partition("l") #=> ["he", "l", "lo"] "hello".partition(/.l/) #=> ["h", "el", "lo"]
"Hello".swapcase #=> "hELLO" "hEllO".upcase #=> "HELLO" "hEllO".downcase #=> "hello" "hello".capitalize #=> "Hello"
HASH
Hash["a", 100, "b", 200] #=> {"a" => 100, "b" => 200} Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a" => 100, "b" => 200} Hash["a" => 100, "b" => 200] #=> {"a" => 100, "b" => 200}
h = { a: 100, b: "word" } # :a and :b are symbols h[:a] #=> 100 h.key("word") #=> :b
h = {"a" => 100, "b" => "word"} h["c"] #=> nil h["a"] #=> 100 h.key(100) #=> "a" h.has_key?("a") #=> true h.has_key?("c") #=> false h.has_value?(100) #=> true h.keys #=> ["a", "b"] h.values #=> [100, "word"] h.assoc("a") #=> ["a", 100] h.rassoc(100) #=> ["a", 100] h.delete("a") #=> {"b" => "word"}
h = { "a" => 100, "b" => 200, "c" => 300 } h.delete_if {|key, value| key >= "b" } #=> {"a" => 100} h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300} h.select {|k,v| v < 200} #=> {"a" => 100} h.each { |k, v| puts "#{k} is #{v}" } h.each_key {|key| print key + " " } #=> "a b c" h.each_value {|v| print v.to_s + " " } #=> "100 200 300" h.invert #=> { 100 => "a", 200 => "b", 300 => "c" }
h1 = { "a" => 100, "b" => 200 } h2 = { "b" => 254, "c" => 300 } h1.merge(h2) #=> { "a" => 100, "b" => 254, "c" => 300 } h1.merge(h2) { |key, v1, v2| v1 } #=> { "a" => 100, "b" => 200, "c" => 300 }
h = { 1 => "a", 2 => "b", 3 => "c" } h.shift #=> [1, "a"] then h is {2=>"b", 3=>"c"} h.to_a #=> [[1, "a"], [2, "b"], [3, "c"]] h.values_at(1, 2) #=> ["a", "b"]
ENUMERATE
%w{ant bear cat}.all? {|word| word.length >= 3} #=> true
[ nil, true, 99 ].all? #=> false
%w{ant bear cat}.any? {|word| word.length >= 3} #=> true
[ nil, true, 99 ].any? #=> true
enum.chunk {|elt| key }.each {|key, arr| ... }
enum.chunk(initial_state) { |elt, state| key }
.each {|key, arr| ... }
[3,1,4,1,5,9,2,6,5,3,5].chunk {|n| n.even? }
.each {|even, arr| p [even, arr] }
#=> [false, [3, 1]]
# [true, [4]]
# [false, [1, 5, 9]] # [true, [2, 6]]
# [false, [5, 3, 5]]
РАЗНОЕ
class Module::ThisIsAClass def this_is_a_method THIS_IS_A_CONSTANT = :this_is_a_symbol this_is_a_local_var = "#{this} #@is a string.\n" this_is_a_float = 10_000.00 this_is_an_integer = 10_000
# TRUE and FALSE are predefined constants. $this_is_a_global_variable = TRUE or FALSE
@this_is_an_instance_variable = `echo '#@hi #{system} call\n' @@this_is_a_class_variable = @@@\\$ # An error. /[0-9]{1,3}
this #{is} a regexp\w+/xi end end