Skip to main content

Posts

Showing posts with the label chars

.map, .fetch, .ord, word indexes, .cycle

- Did encode.rb and duplcate_encoder - .fetch in ruby a = [ 11, 22, 33, 44 ] a.fetch(1)               #=> 22 a.fetch(-1)              #=> 44 a.fetch(4, 'cat')        #=> "cat" a.fetch(4) { |i| i*i }   #=> 16 - .map is the same as .collect - ['a', 'b'].map{|x| '1'} basically replaces the a and b with 1, still in an array - How to combine zip and map https://stackoverflow.com/questions/5609681/ruby-adding-subtracting-elements-from-one-array-with-another-array You could use zip: a = [1,2,3,4] b = [2,3,4,5] a.zip(b).map { |x, y| y - x } # => [1, 1, 1, 1] There is also a Matrix class: require "matrix" a = Matrix[[1, 2, 3, 4]] b = Matrix[[2, 3, 4, 5]] c = b - a # => Matrix[[1, 1, 1, 1]] - .codepoints/ .ord vs bytes https://stackoverflow.com/questions/40849265/bytes-vs-codepoints-in-ruby bytes returns individual bytes, regardless of char size, whereas...

.chars, &:, delete_at, swap, scan

- Did duplicate_count.rb - Learnt .chars actually splits a string into an array of separate characters. But this is case sensitive. - To transform an array of uppercase and lowercase letters to lowercase .select{|item| item.respond_to? :downcase}.map(&:downcase) : before downcase is to see if downcase method exist. - respond_to? is to see if a method exists within a class. https://stackoverflow.com/questions/17893977/confused-about-respond-to-method https://stackoverflow.com/questions/6849722/confused-about-respond-to-vs-respond-to - .downcase works on a string but not array. - .map(&:downcase) is the same as .map { |keyword| keyword.downcase } The &: represents a block. - .group_by groups the hashes in further array depending on condition (1..6).group_by {|i| i%3}   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]} b = ['a','a','b','b'] b.group_by(&:itself) => {"a"=>["a", "a"], ...