InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
Can you print the current day of the week in words such if the current day is Monday then it should print “Monday” in Ruby? |
|
Answer» Ruby is provided with default libraries in the form of classes, which will be accessible after installing ruby in your system. These libraries are referred to as Ruby Standard Library. Some of the libraries need to be invoked explicitly. ‘Date’ class is a library in ruby where you can get most of the actions related to date and make use of these to IMPLEMENT your REQUIREMENT. You need to load the ‘date’ module in file or IRB or console where you want to print the current day of the week. The following example is in IRB, Load ‘date’ class to get the current day of the week in ruby. For example: //----start CODE-------- > load ‘date’ > Date.today.strftime("%A") => "Sunday" //----end code--------From the above example, In the first line, we have loaded the ‘date’ library. Now you will have all the required classes and methods available for you in this IRB console. ‘Date’ is the class that we will be using to get the current day of the week. Date.today will give the current day information such as date, month and year. CALLING strftime method on the current day to FORMAT and get the desired output. In this case, You will use ‘%A’ to get the current day of the week which is ‘Sunday’. There are also many other options to format the date such as get the month in the letter, month in word, year in the letter, year in 4 digits, year in 2 digits, etc Please refer to the following for more formatting options |
|
| 2. |
What is lambda ruby? |
|
Answer» Lambda is an anonymous FUNCTION in ruby, which is also be considered an object in Ruby. You will initialize a lambda and execute it by calling ‘call’ on the initialized VARIABLE. The following example will explain how to initialize and call lambda. //----start code-------- l = lambda { "Hello World" } PUTS l.call > Do or do not //----end code--------You can also pass arguments to a Lambda. The following example gives a basic understanding of lambdas with arguments. //----start code-------- l = lambda do |string| if string == "try" return "There's no such thing" else return "Do or do not." end end puts l.call("try") >There's no such thing //----end code--------You can define a lambda either with do..end or {}. As PER convention followed in Ruby, {} for single line lambdas and do..end for multiline lambdas. |
|
| 3. |
What does ‘self’ mean? |
|
Answer» ‘self ‘ keyword in Ruby is used in different situations depending on the scenario. In other WORDS, Class definition self we can refer to ‘self’ keyword when defining a class in Ruby. We have a Hello class, inside which we’re outputting the VALUE of self: For example: //----start CODE-------- class Hello puts "Self is: #{self}" end //----end code--------When calling ‘self’ directly inside the context of a class definition, the self is equivalent to the parent class in which it was defined; Hello, in the above case. Output is Self is: HelloClass method self A class method is a method that refers only to that class in all contexts. You can define the class method with ‘Self’ keyword. The following example DEMONSTRATES how you can define a class method. //----start code-------- class Hello # Define class variable name = "John Doe" # Getter method def self.name puts "Self inside class method is: #{self}" return name end end puts "Hello class method 'name' is: #{Hello.name}" //----end code--------As explained earlier ‘self’ inside a class method definition refers to that parent class object — Hello in this case. We also call Hello.name in the output, to show that our class method getter behaves as expected: //----start code-------- Self inside a class method is: Hello Hello class method 'name' is: John Doe //----end code-------- |
|
| 4. |
What is the difference between calling super and calling super()? |
|
Answer» A CALL to super INVOKES the parent method with the same arguments that were passed to the child method. An error will THEREFORE occur if the arguments passed to the child method don’t MATCH what the parent is expecting. A call to super() invokes the parent method without any arguments, as PRESUMABLY expected. |
|
| 5. |
Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array. |
|
Answer» There are multiple ways to do this, but one possible ANSWER is: (1..20).INJECT( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) }As you GO up the sequence fib, you sum, or inject(:+), the last two elements in the array and add the result to the end of fib. Note: inject is an ALIAS of reduce |
|
| 6. |
Write a function that sorts the keys in a hash by the length of the key as a string. For instance, the hasht : |
|
Answer» HSH.keys.map(&:to_s).sort_by(&:LENGTH) or: hsh.keys.collect(&:to_s).sort_by { |key| key.length }or : DEF key_sort hsh hsh.keys.collect(&:to_s).SORT { |a, b| a.length <=> b.length } end |
|
| 7. |
What is the difference between nil and false in Ruby? |
|
Answer» nil false nil cannot be a VALUE. false can be a value. nil is returned where there is no predicate. in case of a predicate, true or false is returned by a method. nil is not a boolean DATA TYPE. false is a boolean data type. nil is an OBJECT of nilclass. false is an object of falseclass. |
|
| 8. |
What is the use of load and require in Ruby ? |
|
Answer» In Ruby, load and require both are used for loading the available CODE into the current code. require` reads and parses files only once, when they were referenced for the FIRST time. `load` reads and parses files EVERY time you call `load`. require searches for the library in all the defined search paths and also appends .rb or .so to the file name you enter. It also makes SURE that a library is only included once. So if your application requires library A and B and library B requries library A too A would be loaded only once. With load you need to add the full name of the library and it gets loaded every time you call load - even if it already is in memory |
|
| 9. |
Explain Ruby object and how to create |
Answer»
Object is the default root of all Ruby objects. Ruby objects INHERIT from BasicObject (it is the PARENT class of all classes in Ruby) which allows creating alternate object hierarchie Objects in Ruby are created by calling new method of the class. It is a unique type of method and predefined in the Ruby library. Ruby objects are INSTANCES of the class.
We have a class named Circle. Syntax to create an object circle :
|
|
| 10. |
What are the different ways to compare Ruby string |
|
Answer» Ruby STRINGS can be compared with three operators: |
|
| 11. |
How can the user specify a local gem in Gemfile |
|
Answer» # Add the gem in GEMFILE gem 'rack', :github => 'rack/rack', :branch => 'master'# Execute the below COMMAND in your TERMINAL $ bundle CONFIG local.rack ~/Work/git/rack |
|
| 12. |
What are the different iterators used in Ruby? |
| Answer» | |
| 13. |
What are some built-in Ruby class exceptions. |
|
Answer» Built-in subclasses of EXCEPTION are as FOLLOWS:
|
|
| 14. |
Explain the role of thread pooling in relation to the thread lifecycle in Ruby? |
|
Answer» In Ruby, the lifecycle of a SINGLE thread starts automatically as soon as CPU resources are available. The thread runs the code in the block where it was instantiated and obtains the value of the last EXPRESSION in that block and returns it upon completion. Threads use up resources but running multiple threads at a time can improve an app’s performance. Thread pooling is a technique wherein multiple pre-instantiated reusable threads are left on STANDBY, READY to perform work when needed. Thread pooling is best used when there are a large NUMBER of short tasks that must be performed. This avoids the overhead of having to create a new thread every time a small task is about to be performed. |
|
| 15. |
How would you freeze an object in Ruby? Can you provide a sample example ? |
|
Answer» FREEZE method (Object.freeze) is USED to prevent an object from being changed. water.freeze if( water.frozen? ) PUTS "Water object is a frozen object" ELSE puts "Water object is a normal object" end |
|
| 16. |
Difference between File.new method and File.open method in Ruby? |
|
Answer» Both the methods are used to OPEN a file in Ruby Difference between both the methods is that File.new method cannot be associated with a BLOCK whereas File.open method can be File.new method: Using this method a new file can be created for READING, writing or both. Syntax: F = File.new("fileName.rb") File.open method : Using this method a new file object is created. That file object is ASSIGNED to a file. Syntax: #!/usr/bin/ruby File.open('about', 'w') do |f| f.puts "This is KnowledgeHut" f.write "You are reading Ruby interview questions\n" f << "Please visit our website.\n" end |
|
| 17. |
What is a getter method and how do you create it in Ruby? |
|
Answer» <P>A getter action is a method implementation that GETS the value of an instance variable of an object. With the getter method, you can retrieve the value of an instance variable outside the class. For example: //----start code-------- class Hi def initialize(name) @name = name end end obj1 = Hi.new('Bruno) p obj1.name #=> undefined method `name' for #<Hi:0x007fecd08cb288 @name="Bruno"> (NoMethodError) //----end code--------From the above example, the value of obj1.name cannot be retrieved outside Hi class. if you TRY to retrieve a value of an instance variable outside its class without a getter method, Ruby raises No Method Error. Defining a getter method within a class will MAKE the value of the name variable within the object. It is common practice to name a getter method as the instance variable’s name. //----start code--------- class Hi def initialize(name) @name = name end def name @name end end obj1 = Hi.new('Bruno’) p obj1.name #=> “Bruno” //----end code-------- |
|
| 18. |
What is the difference between a class and a module? |
||||||||||||||
Answer»
|
|||||||||||||||
| 19. |
What is a module? |
|
Answer» A module in ruby has multiple method implementations, various constants, and different class variables. Modules are DEFINED similarly to a class with a module keyword.
Syntax: module Module_name # statements to be executed end For example: # Creating a module with name Hello module Hello # PREFIX with the name of the Module # module method def Hello.welcome puts “Hello!! Welcome” End end # calling the methods of the module Puts Hello.welcome Hello!! Welcome |
|
| 20. |
How do you print an array in reverse order in ruby? |
|
Answer» Ruby has been a human-readable language. Ruby libraries support ALMOST all the IMPLEMENTATIONS. To print an array in REVERSE order in Ruby, you can use a library method called ‘reverse’ over an array, which will print the array in reverse order. The following array is one of the examples to print an array in reverse order with a ‘reverse’ method. For example: //----start CODE---------------- > ('s'..'v').to_a => ["s", "t", "u", "v"] > ('s'..'v').to_a.reverse => ["v", "u", "t", "s"] > ('g'..'v').to_a => ["g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "Q", "r", "s", "t", "u", "v"] > ('g'..'v').to_a.reverse => ["v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g"] //----end code---------------- |
|
| 21. |
How do you define ranges in ruby? |
|
Answer» Ruby has METHODS which can give you required feature without much of actually implementing it. In the question, the requirement is it prints/defines a range of numbers. So it can to print numbers from 1 to 10, 3 to 10, -3 to 4. In the following example, if you notice “.” is a METHOD which is being applied to an object, say 3. In Ruby, everything is an object and ‘3’ is considered as an object. “10” is a method argument to “.” method. Now when you say “(3..10)” will be a block of code and calling “to_a” method with print an array range from 3 to 10. The way to define a specific range in ruby is as follows. //----START code-------- > (3..10).to_a => [3, 4, 5, 6, 7, 8, 9, 10] > (-3..4).to_a => [-3, -2, -1, 0, 1, 2, 3, 4] //----end code--------Ruby has implementations to list range for alphabets. You can say any alphabet say ‘a’, ‘d’ or ‘g’ are objects. “.” is method IMPLEMENTATION. When you (‘a’..’h’) will give a block of code and calling ‘to_a’ will generate an array of alphabets starting from ‘a’ and ends at ‘h’. Example to provide range for alphabets //----start code-------- > ('a'..'h').to_a => ["a", "B", "c", "d", "e", "f", "g", "h"] > ('s'..'v').to_a => ["s", "t", "u", "v"] //----end code-------- |
|
| 22. |
How do you import files or packages or modules in ruby? |
|
Answer» In ruby, we can import with ‘load’ and ‘require’ KEYWORD is used to load packages or modules. The load method INCLUDES the ruby file every time it is being executed. load ‘filename.rb’The COMMONLY used require method includes the ruby file only once. require ‘filename’ require ‘./filename’For example: To import file with ‘require’ keyword Create a file with hello.rb with following code IMPLEMENTATION //--------start code-------------- class Hello def print puts "Hello" end end //-------end code-------------- Now create a new file with name print_hello.rb with following code implementation //------start code-------- require './hello' x = Hello.new x.print //----end code-------- Now run the above file from TERMINAL //----------------- $ ruby print_hello.rb Hello $ //----------- To import file with ‘load’ keyword Create a new file with name print_hello2.rb with following code implementation //------start code-------- load 'hello.rb’ x = Hello.new x.print //----end code-------- Now run the above file from terminal //----------------- $ ruby print_hello2.rb Hello $ //----------- |
|
| 23. |
What type of programming language is Ruby and how is it different from compiled language(Java)? |
|
Answer» Ruby is an open source scripting language and Java is a compiled language. Ruby is mostly focused on simplicity and productivity. Ruby has a simple syntax that is natural to read and easy to write. Ruby is completely free, It is not only free of charge but free to use, copy, modify and distribute. Ruby code is executed only once that is at runtime. Java code is executed TWICE, compile time and runtime. Both Ruby and Java are Object-Oriented Languages. Ruby is DYNAMICALLY typed which means TYPE checking is done at runtime whereas Java is statically typed which means type checking is done to compile time. Ruby the code written will be validated during execution by the interpreter. In Ruby, everything is an Object. Ruby's pure Object-Oriented approach can be demonstrated with an example below 5.times { "Hello Ruby" } You can see how action being applied to a number. Ruby is seen as a FLEXIBLE language, as it allows the users to freely alter its code. Ruby blocks are also seen as a source of flexibility. A programmer can attach a closure to a method, altering how that method should act. the closure is called a block. Unlike other Object-Oriented Languages. Ruby features single inheritance only. Ruby features the concept of modules which adds great flexibility to add methods or variables to required CLASSES. |
|
| 24. |
What are the different class libraries used in Ruby? |
| Answer» | |
| 25. |
Name the three levels of access control for Ruby methods |
Answer»
|
|
| 26. |
How will you rename and delete a file in Ruby? |
|
Answer» Ruby files are renamed USING rename METHOD and deleted using DELETE method . To rename a file, following syntax is USED.
To delete a file, following syntax is used.
============================= |
|