What's the difference between a proc and a lambda in Ruby?
Ans,
One difference is in the way they handle arguments. Creating a proc using
proc {}
and Proc.new {}
are equivalent. However, using lambda {}
gives you a proc that checks the number of arguments passed to it.
They're both methods that create closures, and both return Proc objects.
An example:
p = Proc.new {|a, b| puts a**2+b**2 } # => #<Proc:0x3c7d28@(irb):1>
p.call 1, 2 # => 5
p.call 1 # => NoMethodError: undefined method `**' for nil:NilClass
p.call 1, 2, 3 # => 5
l = lambda {|a, b| puts a**2+b**2 } # => #<Proc:0x15016c@(irb):5 (lambda)>
l.call 1, 2 # => 5
l.call 1 # => ArgumentError: wrong number of arguments (1 for 2)
l.call 1, 2, 3 # => ArgumentError: wrong number of arguments (3 for 2)
Another important but subtle difference is in the way procs created with lambda
and procs created withProc.new
handle the return
statement:
- In a
lambda
-created proc, the return
statement returns only from the proc itself
- In a
Proc.new
-created proc, the return
statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!
Here's lambda
-created proc's return
in action. It behaves in a way that you probably expect:
def whowouldwin
mylambda = lambda {return "Freddy"}
mylambda.call
# mylambda gets called and returns "Freddy", and execution
# continues on the next line
return "Jason"
end
whowouldwin
=> "Jason"
Now here's a Proc.new
-created proc's return
doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:
def whowouldwin2
myproc = Proc.new {return "Freddy"}
myproc.call
# myproc gets called and returns "Freddy",
# but also returns control from whowhouldwin2!
# The line below *never* gets executed.
return "Jason"
end
whowouldwin2
=> "Freddy"
Thanks to this surprising behaviour (as well as less typing), I tend to favour using lambda
overProc.new
when making procs.
What's the big picture difference between observers and callbacks?
Ans:Active Record Callbacks
Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted whendestroy
is called (by overwritingbefore_destroy
) or to massage attributes before they're validated (by overwritingbefore_validation
). As an example of the callbacks initiated, consider theBase#save
call for a new record:save,valid, before_validation, validate, after_validation, before_save,before_create
Observers allow you to factor out code that doesn't really belong in models. For example, a User
model might have a callback that sends a registration confirmation email after the user record is saved, but you don't really want this code in the model because it's not directly related to the model's purpose
3. difference between update attribute and update attributes in rails?
Ans: update attribute bypass validation but update attributes goes through the validation procedures.
Hey please refer toupdate_attribute
. On clicking show source you will get following code# File vendor/rails/activerecord/lib/active_record/base.rb, line 2614 2614: def update_attribute(name, value) 2615: send(name.to_s + '=', value) 2616: save(false) 2617: end
and now referupdate_attributes
and look at its code you get# File vendor/rails/activerecord/lib/active_record/base.rb, line 2621 2621: def update_attributes(attributes) 2622: self.attributes = attributes 2623: save 2624: end
the difference between two isupdate_attribute
usessave(false)
whereasupdate_attributes
usessave
or you can saysave(true)
.
1. update(id,attributes)Update single or multiple objects using update method of active record. When update method invokes it invoke model based validation, save the object when validation passes successfully else object is not save.It requires two argument id and attributes which need to update.Model.update(1,:language => “ruby”,:framework => “rails”)same way you are able to update multiple objects.Model.update([1,2],[{:language => "ruby",:framework => "rails"},{:ide => "aptana"}])2. update_all(attribute, conditions, options)It updates the attribute of object by invoking specified conditions and options like order, limit. But disadvantage of this method is it’s not invoke validation of model.Model.update_all(“language = “ruby”, “framework Like ‘%rails’”,:limit => 2)3. update_attributeThis method update single attribute of object without invoking model based validation.obj = Model.find_by_id(params[:id]) obj.update_attribute :language, “php”4. update_attributesThis method update multiple attribute of single object and also pass model based validation.attributes = {:name => “xyz”, :age => 20} obj = Model.find_by_id(params[:id]) obj.update_attributes(attributes)
Q. In which laguage ruby has been written?
Ans. c
Qus: How to use two databases
into a single application?
Ans: magic
multi-connections allows you to write your model once, and use them
for the multiple rails databases at the same time.
- sudo gem install magic_multi_connection
- After installing this gem, just add this line at bottom of your environment.rb
require “magic_multi_connection”
Qus: How you run your Rails
application without creating databases?
Ans: You can
run your application by uncommenting the line in environment.rb
path=> rootpath conf/environment.rb
config.frameworks- = [action_web_service,
:action_mailer, :active_record]
Qus: How to use sql
db or mysql db without defining it in the database.yml?
[Ans]: You can
use ActiveRecord anywhere
require “rubygems”
require “active_record”
ActiveRecord::Base.establish_connection({
:adapter=>
‘postgresql’, :user=>’foo’, :password=> ‘abc’,
:database=>’whatever’})
Que: Explain why in ruby nil.object_id is equal to 4.
Que: Explain why in ruby nil.object_id is equal to 4.
Ans. Ruby's booleans and nil are objects, so they deserve to be treated like real objects just like the rest. So they too should have an object_id.
When allocating object ids we are restricted with what ids we can use as Fixnum uses the odd object_ids (well all those needed to reach the maximum Fixnum). It takes the odd ids as the least significant bit is always set to 1 to flag this as a Fixnum.
When allocating object ids we are restricted with what ids we can use as Fixnum uses the odd object_ids (well all those needed to reach the maximum Fixnum). It takes the odd ids as the least significant bit is always set to 1 to flag this as a Fixnum.
So starting at the sensible point of 0 this leaves us with the following order:
0 => False 1 => 0 (Fixnum) 2 => True 3 => 1 (Fixnum) 4 => Nil 5 => 2 (Fixnum) 6 => Undefined
http://blog.josephwilk.net/ruby/rubyrails-interview-questions.html
No comments:
Post a Comment