Ruby interview questions
21 questions with answers. 163 open jobs in India ask for Ruby.
How to understand nil vs. empty vs. blank in Ruby?
.nil?can be used on any object and is true if the object is nil..empty?can be used on strings, arrays and hashes and returns true if:- String length == 0
- Array length == 0
- Hash length == 0
Running
.empty?on something that is nil will throw aNoMethodError.That is where
.blank?comes in. It is implemented by Rails and will operate on any object as well as work like.empty?on strings, arrays and hashes.nil.blank? == true false.blank? == true [].blank? == true {}.blank? == true "".blank? == true 5.blank? == false 0.blank? == false.blank?also evaluates true on strings which are non-empty but contain only whitespace:" ".blank? == true " ".empty? == falseRails also provides
.present?, which returns the negation of.blank?.Array gotcha:
blank?will returnfalseeven if all elements of an array are blank. To determine blankness in this case, useall?withblank?, for example:[ nil, '' ].blank? == false [ nil, '' ].all? &:blank? == trueFrom Stack Overflow: asked by Arrel, answered by Corban Brook (CC BY-SA 3.0)
What is attr_accessor in Ruby?
Let's say you have a class
Person.class Person end person = Person.new person.name # => no method errorObviously we never defined method
name. Let's do that.class Person def name @name # simply returning an instance variable @name end end person = Person.new person.name # => nil person.name = "Dennis" # => no method errorAha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. The former is called reader and latter is called writer. We didn't create the writer yet so let's do that.
class Person def name @name end def name=(str) @name = str end end person = Person.new person.name = 'Dennis' person.name # => "Dennis"Awesome. Now we can write and read instance variable
@nameusing reader and writer methods. Except, this is done so frequently, why waste time writing these methods every time? We can do it easier.class Person attr_reader :name attr_writer :name endEven this can get repetitive. When you want both reader and writer just use accessor!
class Person attr_accessor :name end person = Person.new person.name = "Dennis" person.name # => "Dennis"Works the same way! And guess what: the instance variable
@namein our person object will be set just like when we did it manually, so you can use it in other methods.class Person attr_accessor :name def greeting "Hello #{@name}" end end person = Person.new person.name = "Dennis" person.greeting # => "Hello Dennis"That's it. In order to understand how
attr_reader,attr_writer, andattr_accessormethods actually generate methods for you, read other answers, books, ruby docs.From Stack Overflow: asked by dennismonsewicz, answered by Max Chernyak (CC BY-SA 3.0)
Understanding the Rails Authenticity Token
What happens
When the user views a form to create, update, or destroy a resource, the Rails app creates a random
authenticity_token, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for theauthenticity_token, compares it to the one stored in the session, and if they match the request is allowed to continue.Why it happens
Since the authenticity token is stored in the session, the client cannot know its value. This prevents people from submitting forms to a Rails app without viewing the form within that app itself. Imagine that you are using service A, you logged into the service and everything is OK. Now imagine that you went to use service B, and you saw a picture you like, and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to
http://serviceA.example/close_account. This is what is known as CSRF (Cross Site Request Forgery).If service A is using authenticity tokens, this attack vector is no longer applicable, since the request from service B would not contain the correct authenticity token, and will not be allowed to continue.
API docs describes details about meta tag:
CSRF protection is turned on with the
protect_from_forgerymethod, which checks the token and resets the session if it doesn't match what was expected. A call to this method is generated for new Rails applications by default. The token parameter is namedauthenticity_tokenby default. The name and value of this token must be added to every layout that renders forms by includingcsrf_meta_tagsin the HTML head.Notes
Keep in mind, Rails only verifies not idempotent methods (POST, PUT/PATCH and DELETE). GET request are not checked for authenticity token. Why? because the HTTP specification states that GET requests is idempotent and should not create, alter, or destroy resources at the server, and the request should be idempotent (if you run the same command multiple times, you should get the same result every time).
Also the real implementation is a bit more complicated as defined in the beginning, ensuring better security. Rails does not issue the same stored token with every form. Neither does it generate and store a different token every time. It generates and stores a cryptographic hash in a session and issues new cryptographic tokens, which can be matched against the stored one, every time a page is rendered. See request_forgery_protection.rb.
Lessons
Use
authenticity_tokento protect your not idempotent methods (POST, PUT/PATCH, and DELETE). Also make sure not to allow any GET requests that could potentially modify resources on the server.Check the comment by @erturne regarding GET requests being idempotent. He explains it in a better way than I have done here.
From Stack Overflow: asked by Ricardo Acras, answered by Faisal (CC BY-SA 4.0)
What does %w(array) mean?
%w(foo bar)is a shortcut for["foo", "bar"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.From Stack Overflow: asked by Dane O'Connor, answered by sepp2k (CC BY-SA 3.0)
Difference between rake db:migrate db:reset and db:schema:load
db:migrate runs (single) migrations that have not run yet.
db:create creates the database
db:drop deletes the database
db:schema:load creates tables and columns within the existing database following schema.rb. This will delete existing data.
db:setup does db:create, db:schema:load, db:seed
db:reset does db:drop, db:setup
db:migrate:reset does db:drop, db:create, db:migrate
Typically, you would use db:migrate after having made changes to the schema via new migration files (this makes sense only if there is already data in the database). db:schema:load is used when you setup a new instance of your app.
For rails 3.2.12:
I just checked the source and the dependencies are like this now:
db:create creates the database for the current env
db:create:all creates the databases for all envs
db:drop drops the database for the current env
db:drop:all drops the databases for all envs
db:migrate runs migrations for the current env that have not run yet
db:migrate:up runs one specific migration
db:migrate:down rolls back one specific migration
db:migrate:status shows current migration status
db:rollback rolls back the last migration
db:forward advances the current schema version to the next one
db:seed (only) runs the db/seed.rb file
db:schema:load loads the schema into the current env's database
db:schema:dump dumps the current env's schema (and seems to create the db as well)
db:setup runs db:create db:schema:load db:seed
db:reset runs db:drop db:setup
db:migrate:redo runs (db:migrate:down db:migrate:up) or (db:rollback db:migrate) depending on the specified migration
db:migrate:reset runs db:drop db:create db:migrate
For further information please have a look at https://github.com/rails/rails/blob/v3.2.12/activerecord/lib/active_record/railties/databases.rake (for Rails 3.2.x) and https://github.com/rails/rails/blob/v4.0.5/activerecord/lib/active_record/railties/databases.rake (for Rails 4.0.x)
From Stack Overflow: asked by Gaurav Agarwal, answered by moritz (CC BY-SA 4.0)
Why are exclamation marks used in Ruby methods?
In general, methods that end in
!indicate that the method will modify the object it's called on. Ruby calls these as "dangerous methods" because they change state that someone else might have a reference to. Here's a simple example for strings:foo = "A STRING" # a string called foo foo.downcase! # modifies foo itself puts foo # prints modified fooThis will output:
a stringIn the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the
!and one without. The ones without are called "safe methods", and they return a copy of the original with changes applied to the copy, with the callee unchanged. Here's the same example without the!:foo = "A STRING" # a string called foo bar = foo.downcase # doesn't modify foo; returns a modified string puts foo # prints unchanged foo puts bar # prints newly created barThis outputs:
A STRING a stringKeep in mind this is just a convention, but a lot of Ruby classes follow it. It also helps you keep track of what's getting modified in your code.
From Stack Overflow: asked by Lennie, answered by Todd Gamblin (CC BY-SA 3.0)
What's the difference between equal?, eql?, ===, and ==?
I'm going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they're overridden in other classes, like String.
Side note: if you want to try these out for yourself on different objects, use something like this:
class Object def all_equals(o) ops = [:==, :===, :eql?, :equal?] Hash[ops.map(&:to_s).zip(ops.map {|s| send(s, o) })] end end "a".all_equals "a" # => {"=="=>true, "==="=>true, "eql?"=>true, "equal?"=>false}==— generic "equality"At the Object level,
==returns true only ifobjandotherare the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.
===— case equalityFor class Object, effectively the same as calling
#==, but typically overridden by descendants to provide meaningful semantics in case statements.This is incredibly useful. Examples of things which have interesting
===implementations:- Range
- Regex
- Proc (in Ruby 1.9)
So you can do things like:
case some_object when /a regex/ # The regex matches when 2..4 # some_object is in the range 2..4 when lambda {|x| some_crazy_custom_predicate } # the lambda returned true endSee my answer here for a neat example of how
case+Regexcan make code a lot cleaner. And of course, by providing your own===implementation, you can get customcasesemantics.eql?—HashequalityThe
eql?method returns true ifobjandotherrefer to the same hash key. This is used byHashto test members for equality. For objects of classObject,eql?is synonymous with==. Subclasses normally continue this tradition by aliasingeql?to their overridden==method, but there are exceptions.Numerictypes, for example, perform type conversion across==, but not acrosseql?, so:1 == 1.0 #=> true 1.eql? 1.0 #=> falseSo you're free to override this for your own uses, or you can override
==and usealias :eql? :==so the two methods behave the same way.equal?— identity comparisonUnlike
==, theequal?method should never be overridden by subclasses: it is used to determine object identity (that is,a.equal?(b)iffais the same object asb).This is effectively pointer comparison.
From Stack Overflow: asked by denniss, answered by jtbandes (CC BY-SA 4.0)
Ruby: kind_of? vs. instance_of? vs. is_a?
kind_of?andis_a?are synonymous.instance_of?is different from the other two in that it only returnstrueif the object is an instance of that exact class, not a subclass.Example:
"hello".is_a? Objectand"hello".kind_of? Objectreturntruebecause"hello"is aStringandStringis a subclass ofObject.- However
"hello".instance_of? Objectreturnsfalse.
From Stack Overflow: asked by Claudiu, answered by sepp2k (CC BY-SA 4.0)
What does map(&:name) mean in Ruby?
It's shorthand for
tags.map(&:name.to_proc).join(' ')If
foois an object with ato_procmethod, then you can pass it to a method as&foo, which will callfoo.to_procand use that as the method's block.The
Symbol#to_procmethod was originally added by ActiveSupport but has been integrated into Ruby 1.8.7. This is its implementation:class Symbol def to_proc Proc.new do |obj, *args| obj.send self, *args end end endFrom Stack Overflow: asked by collimarco, answered by Josh Lee (CC BY-SA 3.0)
Why use Ruby's attr_accessor, attr_reader and attr_writer?
You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.
class Person attr_accessor :age ... endHere, I can see that I may both read and write the age.
class Person attr_reader :age ... endHere, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.
But what is happening behind the scenes?
If you write:
attr_writer :ageThat gets translated into:
def age=(value) @age = value endIf you write:
attr_reader :ageThat gets translated into:
def age @age endIf you write:
attr_accessor :ageThat gets translated into:
def age=(value) @age = value end def age @age endKnowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?
From Stack Overflow: asked by Saturn, answered by Wayne Conrad (CC BY-SA 3.0)
Should Gemfile.lock be included in .gitignore?
Update for 2022 from TrinitronX
Fast-forward to 2021 and now Bundler docs [web archive] now say to commit the Gemfile.lock inside a gem... ¯\_(ツ)_/¯ I guess it makes sense for developers and ease of use when starting on a project. However, now CI jobs need to be sure to remove any stray Gemfile.lock files to test against other versions.
Legacy answer ~2010
Assuming you're not writing a rubygem, Gemfile.lock should be in your repository. It's used as a snapshot of all your required gems and their dependencies. This way bundler doesn't have to recalculate all the gem dependencies each time you deploy, etc.
From cowboycoded's comment below:
If you are working on a gem, then DO NOT check in your Gemfile.lock. If you are working on a Rails app, then DO check in your Gemfile.lock.
Here's a nice article explaining what the lock file is.
From Stack Overflow: asked by aarona, answered by rwilliams (CC BY-SA 4.0)
What is the difference between include and require in Ruby?
What's the difference between "include" and "require" in Ruby?
Answer:
The include and require methods do very different things.
The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.
The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use
require.Oddly enough, Ruby's
requireis analogous to C'sinclude, while Ruby'sincludeis almost nothing like C'sinclude.From Stack Overflow: asked by Owen, answered by HanClinto (CC BY-SA 3.0)
When monkey patching an instance method, can you call the overridden method from the new implementation?
EDIT: It has been 9 years since I originally wrote this answer, and it deserves some cosmetic surgery to keep it current.
You can see the last version before the edit here.
You can’t call the overwritten method by name or keyword. That’s one of the many reasons why monkey patching should be avoided and inheritance be preferred instead, since obviously you can call the overridden method.
Avoiding Monkey Patching
Inheritance
So, if at all possible, you should prefer something like this:
class Foo def bar 'Hello' end end class ExtendedFoo < Foo def bar super + ' World' end end ExtendedFoo.new.bar # => 'Hello World'This works, if you control creation of the
Fooobjects. Just change every place which creates aFooto instead create anExtendedFoo. This works even better if you use the Dependency Injection Design Pattern, the Factory Method Design Pattern, the Abstract Factory Design Pattern or something along those lines, because in that case, there is only place you need to change.Delegation
If you do not control creation of the
Fooobjects, for example because they are created by a framework that is outside of your control (like ruby-on-rails for example), then you could use the Wrapper Design Pattern:require 'delegate' class Foo def bar 'Hello' end end class WrappedFoo < DelegateClass(Foo) def initialize(wrapped_foo) super end def bar super + ' World' end end foo = Foo.new # this is not actually in your code, it comes from somewhere else wrapped_foo = WrappedFoo.new(foo) # this is under your control wrapped_foo.bar # => 'Hello World'Basically, at the boundary of the system, where the
Fooobject comes into your code, you wrap it into another object, and then use that object instead of the original one everywhere else in your code.This uses the
Object#DelegateClasshelper method from thedelegatelibrary in the stdlib.“Clean” Monkey Patching
Module#prepend: Mixin PrependingThe two methods above require changing the system to avoid monkey patching. This section shows the preferred and least invasive method of monkey patching, should changing the system not be an option.
Module#prependwas added to support more or less exactly this use case.Module#prependdoes the same thing asModule#include, except it mixes in the mixin directly below the class:class Foo def bar 'Hello' end end module FooExtensions def bar super + ' World' end end class Foo prepend FooExtensions end Foo.new.bar # => 'Hello World'Note: I also wrote a little bit about
Module#prependin this question: Ruby module prepend vs derivationMixin Inheritance (broken)
Read the rest at the sourceFrom Stack Overflow: asked by James Hollingworth, answered by Jörg W Mittag (CC BY-SA 4.0)
What is the difference between include and extend in Ruby?
What you have said is correct. However, there is more to it than that.
If you have a class
Klazzand moduleMod, includingModinKlazzgives instances ofKlazzaccess toMod's methods. Or you can extendKlazzwithModgiving the classKlazzaccess toMod's methods. But you can also extend an arbitrary object witho.extend Mod. In this case the individual object getsMod's methods even though all other objects with the same class asodo not.From Stack Overflow: asked by Gishu, answered by domgblackwell (CC BY-SA 4.0)
Is there a "do ... while" loop in Ruby?
CAUTION:
The
begin <code> end while <condition>is rejected by Ruby's author Matz. Instead he suggests usingKernel#loop, e.g.loop do # some code here break if <condition> endHere's an email exchange in 23 Nov 2005 where Matz states:
|> Don't use it please. I'm regretting this feature, and I'd like to |> remove it in the future if it's possible. | |I'm surprised. What do you regret about it? Because it's hard for users to tell begin <code> end while <cond> works differently from <code> while <cond>RosettaCode wiki has a similar story:
During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.
From Stack Overflow: asked by Paige Ruten, answered by Siwei (CC BY-SA 4.0)
What is Ruby's double-colon `::`?
::is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:module SomeModule module InnerModule class MyClass CONSTANT = 4 end end endYou could access
CONSTANTfrom outside the module asSomeModule::InnerModule::MyClass::CONSTANT.It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot
.).Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes
From Stack Overflow: asked by Meltemi, answered by mipadi (CC BY-SA 3.0)
When to use RSpec let()?
I always prefer
letto an instance variable for a couple of reasons:- Instance variables spring into existence when referenced. This means that if you fat finger the spelling of the instance variable, a new one will be created and initialized to
nil, which can lead to subtle bugs and false positives. Sinceletcreates a method, you'll get aNameErrorwhen you misspell it, which I find preferable. It makes it easier to refactor specs, too. - A
before(:each)hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined bylet, the initialization code only runs if the example calls it. - You can refactor from a local variable in an example directly into a let without changing the
referencing syntax in the example. If you refactor to an instance variable, you have to change
how you reference the object in the example (e.g. add an
@). - This is a bit subjective, but as Mike Lewis pointed out, I think it makes the spec easier to read. I like the organization of defining all my dependent objects with
letand keeping myitblock nice and short.
A related link can be found here: http://www.betterspecs.org/#let
From Stack Overflow: asked by sent-hil, answered by Myron Marston (CC BY-SA 4.0)
- Instance variables spring into existence when referenced. This means that if you fat finger the spelling of the instance variable, a new one will be created and initialized to
How to write a switch statement in Ruby?
Ruby uses the
caseexpression instead.case x when 1..5 "It's between 1 and 5" when 6 "It's 6" when "foo", "bar" "It's either foo or bar" when String "You passed a string" else "You gave me #{x} -- I have no idea what to do with that." endRuby compares the object in the
whenclause with the object in thecaseclause using the===operator. For example,(1..5) === x, and notx === (1..5).This allows for sophisticated
whenclauses as seen above. Ranges, classes and all sorts of things can be tested for rather than just equality.Unlike
switchstatements in many other languages, Ruby’scasedoes not have fall-through, so there is no need to end eachwhenwith abreak. You can also specify multiple matches in a singlewhenclause likewhen "foo", "bar".From Stack Overflow: asked by readonly, answered by Chuck (CC BY-SA 4.0)
How to check if a value exists in an array in Ruby?
You're looking for
include?:>> ['Cat', 'Dog', 'Bird'].include? 'Dog' => trueFrom Stack Overflow: asked by user211662, answered by Brian Campbell (CC BY-SA 3.0)
How to call shell commands from Ruby?
This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link.
First, note that when Ruby calls out to a shell, it typically calls
/bin/sh, not Bash. Some Bash syntax is not supported by/bin/shon all systems.Here are ways to execute a shell script:
cmd = "echo 'hi'" # Sample string that can be usedKernel#`, commonly called backticks –`cmd`This is like many other languages, including Bash, PHP, and Perl.
Returns the result (i.e. standard output) of the shell command.
Docs: http://ruby-doc.org/core/Kernel.html#method-i-60
value = `echo 'hi'` value = `#{cmd}`Built-in syntax,
%x( cmd )Following the
xcharacter is a delimiter, which can be any character. If the delimiter is one of the characters(,[,{, or<, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation#{ ... }is allowed.Returns the result (i.e. standard output) of the shell command, just like the backticks.
Docs: https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings
value = %x( echo 'hi' ) value = %x[ #{cmd} ]Kernel#systemExecutes the given command in a subshell.
Returns
trueif the command was found and run successfully,falseotherwise.Docs: http://ruby-doc.org/core/Kernel.html#method-i-system
wasGood = system( "echo 'hi'" ) wasGood = system( cmd )Kernel#execReplaces the current process by running the given external command.
Returns none, the current process is replaced and never continues.
Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec
exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above
Here's some extra advice:
$?, which is the same as$CHILD_STATUS, accesses the status of the last system executed command if you use the backticks,system()or%x{}. You can then access theexitstatusandpidproperties:$?.exitstatusFor more reading see:
From Stack Overflow: asked by CodingWithoutComments, answered by Steve Willard (CC BY-SA 4.0)
How to convert a string to lower or upper case in Ruby?
Ruby has a few methods for changing the case of strings. To convert to lowercase, use
downcase:"hello James!".downcase #=> "hello james!"Similarly,
upcasecapitalizes every letter andcapitalizecapitalizes the first letter of the string but lowercases the rest:"hello James!".upcase #=> "HELLO JAMES!" "hello James!".capitalize #=> "Hello james!" "hello James!".titleize #=> "Hello James!" (Rails/ActiveSupport only)If you want to modify a string in place, you can add an exclamation point to any of those methods:
string = "hello James!" string.downcase! string #=> "hello james!"Refer to the documentation for String for more information.
From Stack Overflow: asked by Heat Miser, answered by Sophie Alpert (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA21 questions