Showing posts from 2018

Ruby 2.5 Major Changes

1. rescue/else/ensure are allowed inside do/end blocks without begin/end 2. Print backtrace and error message in reverse order (experimental) 3. Kernel#yield_self           2.yield_self { |n| n * 10 } #=> 20           names = ['Alice', 'Bob']            names.join(', ').yield_self { |s| "(#{s})" }           #=> "(Alice, Bob)" 4. String#delete_prefix/delete_suffix 5. Array#prepend/append as aliases of unshift/push 6. Hash#transform_keys/transform_keys!

Prime Number with out Prime Class

a = [1,4,5,12,9,5,3,5] class Array   def prime_numbers   end end class Integer   def prime?     return if self <= 1     (2..Math.sqrt(self).ceil).none? { |i| (self % i).zero? }   end end  a.prime_numbers => [5, 5, 3, 5]

Ruby's class_eval & instance_eval. Is it that confusing?

We can do class_eval & instance_eval using following syntax, In this example, class_eval? method can be accessed my any objects of the String class. Where as instance_eval? method can be accessed by only String class.  More clearly, class_eval creates instance methods, but instance_eval creates class methods or it can be applied to only one object at a time. [3] pry(main)> String.class_eval? NoMethodError: undefined method `class_eval?' for String:Class Did you mean?  class_eval from (pry):3:in `<main>' [4] pry(main)> String.instance_eval? => true [5] pry(main)> => true my_string = "This is a string" For example you can simply do like below as any string is an object of String Class [5] pry(main)>  my_string .class_eval? => true But you can not do  [7] pry(main)> my_string.instance_eval? NoMethodError: undefined method `instance_eval?' for "This is a string":String