Quiz - August Flashcards
How can you run some ruby script without IRB or ruby file?
We can use the -e tag against the ruby command.
Example :
> ruby -e ‘puts “Ruby programming”’
What would be the output of the code?
puts “This statement comes later”
BEGIN {
puts “This statement will be printed in the beginning”
}
This statement will be printed in the beginning
This statement comes later
It is possible to print multi-line strings using print in Ruby?
yes
We can use EOF or EOC with print
What would be the output?
”[%s]” % “same old drag”
”[%s]” % “same old drag”
# => “[same old drag]”
Quick string interpolation
x = %w{p hello p}
“%s%s>” % x
is this valid?
yes # => "<p>hello</p>"
a = %w{a b} b = %w{c d} what is the output of this code? [a + b] [*a + b]
[a + b] # => [[“a”, “b”, “c”, “d”]]
[*a + b] # => [“a”, “b”, “c”, “d”]
does = is = { true => ‘Yes’, false => ‘No’ }
is this valid ?
does[10 == 50]
is[10 > 5]
It’s rare you see anyone use non-strings or symbols as hash keys. It’s totally possible though, and sometimes handy :
does = is = { true => ‘Yes’, false => ‘No’ }
does[10 == 50] # => “No”
is[10 > 5] # => “Yes”
require ‘rubygems’
require ‘activemerchant’
require ‘date’
If we have more required modules, shall we use any shortcut code for this?
you can take this to extremes using Ruby’s enumerators to perform similar operations multiple times. Consider requiring multiple files, for instance:
%w{rubygems daemons eventmachine}.each { |x| require x }
qty = 1
qty == 0 ? ‘none’ : qty == 1 ? ‘one’ : ‘many’
is this valid code?
What would be the output?
“one”
ternary operators can be nested within each other
How to skip this error?
for example
h = { :age => 10 }
h[:name].downcase =>Error
yes.
You can use rescue in its single line form to return a value when other things on the line go awry:
h = { :age => 10 }
h[:name].downcase # ERROR
h[:name].downcase rescue “No name” # => “No name”
How to delete directories with files in Ruby?
To delete directories, Ruby comes with a handy file utility library called FileUtils that can do the hard work:
require ‘fileutils’
FileUtils.rm_r ‘somedir’
money = 9.5 cost = 100
How to convert to “9.50” and “100.00”?
Formatting floating point numbers into a form used for prices can be done with sprintf or, alternatively, with a formatting interpolation:
a = %w{a b c d e f g h} b = [0, 5, 6]
a. values_at(b[0])
a. values_at(b[1])
a. values_at(b[2]) # a , f, g
How to get the values in one shot?
a = %w{a b c d e f g h}
b = [0, 5, 6]
a.values_at(*b).inspect
use explode
Which one is correct?
def is_odd(x) x % 2 == 0 ? false : true end
def is_odd(x)
x % 2 != 0
end
Both are correct
How to convert “to_boolean” of any value?
!! “hello”
!! nil
double bang
!!"hello" #-> this is a string that is forced into a boolean # context (true), and then negated (false), and then # negated again (true) !!nil #-> this is a false-y value that is forced into a boolean # context (false), and then negated (true), and then # negated again (false)