Tag: ruby
Like JavaScript anonymous undefined functions
With the yield statement
With the yield statement
def test puts "You are in the method" yield puts "You are again back to the method" yield end test {puts "You are in the block"} def test yield 5 puts "You are in the method test" yield 100 end test {|i| puts "You are in the block #{i}"}
With each on array
array.each do |element| puts element end
Reduce
The above functions/methods take in an array, multiply all the elements together, then return the result. The main idea behind reduce is taking a bunch of things and reducing them down to a single value.
The above functions/methods take in an array, multiply all the elements together, then return the result. The main idea behind reduce is taking a bunch of things and reducing them down to a single value.
# Ruby def getProduct(array) array.reduce do |accumulator, element| accumulator * element end end // JavaScript const getProduct = array => { return array.reduce((accumulator, element) => { return accumulator * element }) }
Filter/Select
The main idea behind filter / select is passing each element to a block; if the element makes the block truthy, the element is added to a new array.
The main idea behind filter / select is passing each element to a block; if the element makes the block truthy, the element is added to a new array.
# Ruby def getOddNums(array) array.select { |element| element % 2 != 0 } end // JavaScript const getOddNums = array => { return array.filter((element) => { return element % 2 !== 0 }) }
Map
array = ["11", "21", "5"] array.map { |str| str.to_i } # [11, 21, 5] hash = { bacon: "protein", apple: "fruit" } hash.map { |k,v| [k, v.to_sym] }.to_h # {:bacon=>:protein, :apple=>:fruit}