Skip to content

Instantly share code, notes, and snippets.

@mykiy
mykiy / ruby test
Last active April 8, 2018 18:58
Test ruby
1) Explain calling super and calling super() and give some example?
super and super() both inherits methods from parent class. super allows the arguments but super() dont allow the arguments.
Ex:
--
class Niyati
def process(person,work)
"I am #{person} and am a #{work}"
end
end
@mykiy
mykiy / json
Last active April 5, 2018 10:34
json
=> name/value pairs
{
"name":"value"
}
=> supports
number, strings, boolean, nil, array
=>
{
"name":"value",
"array": [ 1,2,3 ],
@mykiy
mykiy / hash
Last active April 5, 2018 12:02
hash and symbol
arr = [4,1,2,7,"M","A","V"]
arr.partition { |a| a.is_a? String }.map(&:sort).flatten
p arr
=>
["A","V","M",1,2,4,7]
-------
a = [1, "A", nil, "M", "", '']
a.reject!{|a| a.nil? || a.to_s.empty? }
p a
=>
movies = {
Ravanan: 4.8,
Thanioruvan: 4.5,
payanangal: 4
}
puts "What would you like to do?"
puts "-- Type 'add' to add a movie."
puts "-- Type 'update' to update a movie."
puts "-- Type 'display' to display all movies."
arr = [1,2,3,4,5]
arr.each { |n| n + 2 }
arr
=> [1,2,3,4,5]
arr.map! { |n| n + 2 }
arr
=>
[3,4,5,6,7]
arr.collect! { |n| n + 2 }
arr
@mykiy
mykiy / blocks
Last active April 3, 2018 11:43
reduce block in ruby
#reduce
def sum(*args) #sum method accepts many number of arguments that method passed
args.reduce(0, :+) #reduce will reduce the array in single number, 0 is the initial value and + tells the reduce method to perform addition
end
sum(1,2,3,4)
=>
10
-----
multiplication
@mykiy
mykiy / lambda
Last active April 3, 2018 11:36
lambda in ruby
l = -> (name) { puts "#{name}" }
l.call("velu")
=>
velu
--------
l = -> (num) { num * 5 } # l is the variable which stores the block of code, when we calls the l the block of code will be executed.
l.call(5) #Another important thing is lambda is an object.
=>
25
@mykiy
mykiy / procs
Created April 3, 2018 10:57
procs in ruby
p = Proc.new do #proc is a object, actually a block of code stored in a instance variable
"hello"
end
p.call
-----
p = Proc.new do |num|
num * num
end
class Work
def initialize(name)
@name = name
end
def name
@name
end
def name=(name)
@name = name
end
class Work
attr_accessor :name, :duration
end
job = Work.new("ROR learning", "1month")
job.name
=> "ROR learning"
job.name = "Ruby learning"
job.name
=> "Ruby learning"