>> x = { :a => 1, :b => 2 } => {:b=>2, :a=>1} >> x.keys => >> x.values => >> x[:c] = 3 => 3 >> x => >> x.delete('a') => nil >> x => >> x.delete(:a) => 1 >> x => >> x = { :a => 1, :b => 2, :c => 4 } => {:b=>2, :c=>4, :a=>1} >> x.delete_if { |k,v| v % 2 == 0 } => >> x => >> z = { :a => [1, { :b => { :c => 2 }}], :e => lambda { |x| x*x } } => {:e=>#<Proc:0x00000001012c5108@(irb):18>, :a=>[1, {:b=>{:c=>2}}]} >> z[:a][1][:b][:c] => >> z[:e] => #<Proc:0x00000001012c5108@(irb):18> >> z[:e].class => Proc >> Proc.instance_methods(false) => ["dup", "[]", "==", "to_s", "binding", "clone", "arity", "to_proc", "call"] >> z[:e].call(4) => >> z[:e][9] => >> z[:e][4] =>
>> f = lambda { |x,y| x * y } => #<Proc:0x000000010128a4b8@(irb):17> >> f.arity =>
mult
?
~/rubytesting$ cat -n closure.rb 1 def mult(n) 2 lambda { |v| v.map { |x| x * n } } 3 end 4 5 doubler = mult(2) 6 puts doubler[[1,2,3]]¿Cuál es la salida?
~/rubytesting$ cat -n sharedvarandclosure.rb 1 def accessor_pair(initialValue = nil) 2 value = initialValue 3 4 getter = lambda { value } 5 setter = lambda { |x| value = x } 6 return getter, setter 7 end 8 9 10 getX, setX = accessor_pair(9) 11 puts getX[] 12 13 setX[-1] 14 puts getX[]¿Que retorna
accessor_pair
?
Cómo es que la variable value
no es destruída por el garbage
collector de Ruby cuando se termina el ámbito de accessor_pair
?
>> a = (1..5).to_a => >> a = a.collect { |x| x*x } => >> b = a.select { |y| (4..16).include? y } =>
c
?
>> a = (1..5).to_a => >> c = a.inject(1) { |x,y| x *= y } =>
>> "%d %s" % [3, "rubies"] =>
>> x, y = 4, 5 => >> z = x > y ? x : y => >> x,y,z = [1,2,3] =>
>> z = %x{ls}.split(/\s+/).select { |w| w =~ /ruby/i } => >> /ruby/i === "Ruby" =>
1.5
, -2.3
, -4.7e-1
, etc.)
>> str = "Hello 'name'" => "Hello 'name'" >> name = "John" => "John" >> str.gsub(/'([^']*)'/) { eval($1) } => "Hello John"
>> "hello".index /e/ => 1 >> "hello".index /h/ => 0 >> "hello".index /n/ => nil >> "hello".index /o/ => 4
attr_accessor
? ¿ Que argumentos lleva?
attr_reader
? ¿ Que argumentos lleva?
attr_writer
? ¿ Que argumentos lleva?
yield 4, 5
?
p
de una clase ser llamado x.p()
desde un objeto x
de una subclase?
p
de una clase ser llamado x.p()
desde un objeto x
de una subclase?
Casiano Rodriguez León 2015-01-07