Interview :: Ruby
In how many ways a block is written in Ruby?
A block is written in two ways:
- Multi-line between do and end
- Inline between braces {}
Both are same and have the same functionality.
syntax:
What is yield statement in Ruby?
The yield statement is used to call a block within a method with a value.
Explain ampersand parameter () in Ruby?
The is a way to pass a reference (instead of a local variable) to the block to a method.
Here, block word after the & is just a name for the reference, any other name can be used instead of this.
Explain Ruby module?
Ruby module is a collection of methods and constants. A module method may be instance method or module method. They are similar to classes as they hold a collection of methods, class definitions, constants and other modules. They are defined like classes. Objects or subclasses can not be created using modules. There is no module hierarchy of inheritance.
Modules basically serve two purposes:
- They act as namespace. They prevent the name clashes.
- They allow the mixin facility to share functionality between classes.
Syntax:
Module name should start with a capital letter.
Explain module mixins in Ruby?
Ruby doesn't support multiple inheritance. Modules eliminate the need of multiple inheritance using mixin in Ruby.
A module doesn't have instances because it is not a class. However, a module can be included within a class.
When you include a module within a class, the class will have access to the methods of the module.
Explain Ruby strings?
Ruby string object holds and manipulates an arbitary sequence of bytes, typically representing characters. They are created using String::new or as literals.
How to access Ruby strings elements in an application?
You can access Ruby string elements in different parts with the help of square brackets []. Within square brackets write the index or string.
How to write multiline string in Ruby.
Writing multiline string is very simple in Ruby language. We will show three ways to print multiline string.
- String can be written within double quotes.
- The % character is used and string is enclosed within / character.
- In heredoc syntax, we use
The global variable is declared in Ruby that you can access it anywhere within the application because it has full scope in the application. The global variables are used in Ruby with $ prepend.
What is concatenating string in Ruby. In how many ways you can create a concatenating string?
Ruby concatenating string implies creating one string from multiple strings. You can join more than one string to form a single string by concatenating them.
There are four ways to concatenate Ruby strings into single string:
- Using plus sign in between strings.
- Using a single space in between strings.
- Using
- Using concat method in between strings.