rubybeginner
Ruby Basics
Variables, blocks and classes
6 questions
By EZ4Code Team
1. What is the common method to output to the console in Ruby?
puts
print
console.log
echo
Explanation: puts outputs with an automatic newline; print outputs without a newline; p outputs in inspect form (for debugging).
2. What are the naming prefixes for local variables, instance variables, and class variables in Ruby?
Local variables have no prefix, instance variables @, class variables @@
Local variables $, instance variables @, class variables @@
Local variables have no prefix, instance variables @@, class variables @
All three have no prefix
Explanation: Local variables start with a lowercase letter and have no prefix; @var for instance variables; @@var for class variables; $var for global variables.
3. What are the two ways to write blocks in Ruby?
{ } and do...end
() and {}
begin...end and {}
do...while and for
Explanation: Blocks can use curly braces { |x| ... } (preferred for single-line) or do |x| ... end (preferred for multi-line), receiving arguments passed by yield.
4. What does the following code output? [1,2,3].each { |n| puts n }
[1,2,3].each { |n| puts n }1 2 3 (each on its own line)
[1,2,3]
6
Error
Explanation: each iterates over each element of the array and passes it to the block; the block parameter |n| receives it, and puts n prints 1, 2, 3 in turn, each on its own line.
5. What is the keyword to define a class in Ruby?
class
Class
def class
type
Explanation: Use class Name ... end to define a class; class names are conventionally capitalized. Methods are defined with def.
6. What are the characteristics of a Symbol like :name in Ruby?
Immutable interned strings, often used as hash keys, unique in memory
Mutable strings
Numeric type
Equivalent to strings
Explanation: A Symbol is an immutable, memory-unique object, suitable as a hash key or enumeration, more efficient than strings; strings are mutable and create a new object each time.