Ruby Intro - General Flashcards
What do you call a method with exclamation point? 2 answers.
Bang version of the method or unsafe method.
What is a module and give an example.
A module is a collection of methods (and constants). Modules can be mixed in to other classes; this just means that the module’s methods are available in the class that it is mixed into.
Enumerable is one of the most powerful modules because it holds Each and Map. It is also mixed into other classes like Arrays and Hash, it’s also available to those classes as well.
What is difference between gsub and sub?
gsub is “general” sub and replaces all instances. sub only replaces first instance.
What is difference between inspect and to_s?
Inspect returns valid ruby code for debugging purposes (always surrounded by quotes). to_s transforms to string and is used as part of program (sometimes in quotes).
[1, 2, 3].to_s # => “[1, 2, 3]”
“my_string”.to_s # => “my_string” (already a string)
nil.to_s # => “” (nil represented as nothing, or emptiness)
[1, 2, 3].inspect # => “[1, 2, 3]” (same as to_s)
“my_string”.inspect # => ‘“my_string”’ (notice the quotes)
nil.inspect # => “nil”
What is the difference between puts and p?
Puts is like to_s. It prints out the string. ‘p’ is like inspect. It prints out the ruby code for debugging purposes (always in quotes).
puts “my string!” # prints “my string!”
p “my string!” # prints ‘“my string!”’
puts nil # => prints a blank line
p nil # => prints “nil”
What is a Kernel module?
Methods that are defined at the top level scope are methods of the Kernel module. The Kernel module is mixed into every class, so that you may call these “global” methods from any context. Puts and gets are kernel.
How do you use nil?
puts “Couldn’t find answer” if [1, 2, 3].index(42).nil?
How do you use class method?
Tells you what kind of class an object is:
“string”.class # => String
3.class # => Fixnum
When creating a method, how do you define a default parameter (when none is received)?
def h(name = “default”)
What is general rule for nesting loops?
Nesting 2 loops is ok. But more is generally bad. You should create methods if you need to have deeply nested loops.
A good method has what 3 characteristics?
does one thing, short descriptive name, <10 lines of code
How do you do a conditional assignment (that is, assign value to a variable only if it is empty)
array ||= [1]
is the same as
array = [1] if array.nil?
How is “return” treated different in Ruby methods as opposed to Javascript functions?
In Ruby, return is implicit, meaning it’s not necessary to type in. In Javascript, you must type in “return” otherwise you will get an “undefined.” In Python, no “return” returns “None.”
How do you use the “times” method? Sample code.
3.times {code here}
What two common looping methods are not used much in Ruby? And what are their better alternatives?
For..in and Loop… methods.
The For..in loop is better served in Ruby by the .times or .each or .upto/.downto methods