Skip to content

Instantly share code, notes, and snippets.

class Work
def name=(name) #which works like a setter method of class
@name = name
end
def name #which works like a gettter method, gets the name from current object scope
@name
end
end
job = Work.new #which creates the new instance object
class Work
def initialize(name) #when instance object created, the object calls the inititalize method and initiated the valur to instance variables
@name = name
end
def duration=(time)
@duration = time
end
def duration
@duration
end
class Work
attr_accessor :name, :duration
def intialize(name, duration)
@name, @duration = name, duration
end
end
job = Work.new("ROR learning", "1month")
job.name
=> "ROR learning"
job.duration
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"
class Work
def initialize(name)
@name = name
end
def name
@name
end
def name=(name)
@name = name
end
@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
@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 / 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
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
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."