Fundamentals Flashcards
What does .include? return
if string_to_check.include? “substring”
It evaluates to true if it finds what it’s looking for and false otherwise.
As a general rule, Ruby methods that end with ? evaluate to what?
As a general rule, Ruby methods that end with ? evaluate to the boolean values true or false.
Explain what gsub does and what inputs it takes
gsub(pattern, replacement) → new_str click to toggle source
gsub(pattern, hash) → new_str
gsub(pattern) {|match| block } → new_str
gsub(pattern) → enumerator
Returns a copy of str with the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. ‘\d’ will match a backlash followed by ‘d’, instead of a digit.
If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d, where d is a group number, or \k, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as $&, will not refer to the current match.
If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.
In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $’ will be set appropriately. The value returned by the block will be substituted for the match on each call.
The result inherits any tainting in the original string or any supplied replacement string.
When neither a block nor a second argument is supplied, an Enumerator is returned.
“hello”.gsub(/[aeiou]/, ‘’) #=> “hll”
“hello”.gsub(/([aeiou])/, ‘’) #=> “hll”
“hello”.gsub(/./) {|s| s.ord.to_s + ‘ ‘} #=> “104 101 108 108 111 “
“hello”.gsub(/(?[aeiou])/, ‘{\k}’) #=> “h{e}ll{o}”
‘hello’.gsub(/[eo]/, ‘e’ => 3, ‘o’ => ‘’) #=> “h3ll*”
What is the difference between 1..10 and 1…10
Two dots includes last number
Three dots does not include last number
What are two ways to create a hash?
h = Hash.new h["keyname"] = "valuename"
h = { “keyname” => “valuename”}
What input does split take and what does it return?
Divides str into substrings based on a delimiter, returning an array of these substrings.
If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.
If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.
When the input str is empty an empty Array is returned as the string is considered to have no fields to split.
” now’s the time”.split #=> [“now’s”, “the”, “time”]
“ now’s the time”.split(‘ ‘) #=> [“now’s”, “the”, “time”]
“ now’s the time”.split(/ /) #=> [””, “now’s”, “”, “the”, “time”]
“1, 2.34,56, 7”.split(%r{,\s}) #=> [“1”, “2.34”, “56”, “7”]
“hello”.split(//) #=> [“h”, “e”, “l”, “l”, “o”]
“hello”.split(//, 3) #=> [“h”, “e”, “llo”]
“hi mom”.split(%r{\s}) #=> [“h”, “i”, “m”, “o”, “m”]
“mellow yellow”.split(“ello”) #=> [“m”, “w y”, “w”]
“1,2,,3,4,,”.split(‘,’) #=> [“1”, “2”, “”, “3”, “4”]
“1,2,,3,4,,”.split(‘,’, 4) #=> [“1”, “2”, “”, “3,4,,”]
“1,2,,3,4,,”.split(‘,’, -4) #=> [“1”, “2”, “”, “3”, “4”, “”, “”]
”“.split(‘,’, -1) #=> []
How do you set a default value for a Hash?
If you have a hash with a default value, and you try to access a non-existent key, you get that default value.
h = Hash.new(“nothing here”)
puts h # {}
puts h["kitty"] # nothing here
Write a program that takes a user input
Splits the input into separate words
Add those words to a Hash
Puts the word and the amount of times it appears
puts ‘input’
text = gets.chomp
words = text.split(“ “)
frequencies = Hash.new(0)
words.each do |word|
frequencies[word] += 1
end
frequencies = frequencies.sort_by do |word, count|
count
end
frequencies.reverse!
frequencies.each do |key, value|
puts “#{key} #{value}”
end
What are splat arguments?
Splat arguments are arguments preceded by a *, which signals to Ruby: “Hey Ruby, I don’t know how many arguments there are about to be, but it could be more than one.”
What is the combined comparison operator and how does it work?
The combined comparison operator looks like this: <=>. It returns 0 if the first operand (item to be compared) equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.
How would you sort an array called books in descending order?
books.sort! { |a, b| b <=> a}
What does rev=false mean in this method?
def alphabetize(arr, rev=false)
What this does is tell Ruby that alphabetize has a second parameter, rev (for “reverse”) that will default to false if the user doesn’t type in two arguments.
What are the only two non-true values in Ruby?
false
nil
What happens if you try to access a key that doesn’t exist, though?
In many languages, you’ll get an error of some kind. Not so in Ruby: you’ll instead get the special value nil.
What does nil mean
It means “nothing at all”
What are 3 reasons why Symbols make good hash keys?
They’re immutable, meaning they can’t be changed once they’re created;
Only one copy of any symbol exists at a given time, so they save memory;
Symbol-as-keys are faster than strings-as-keys because of the above two reasons.
What method do you use to iterate over only Hash keys and what method do you use to iterate over only Hash values?
Ruby includes two hash methods, .each_key and .each_value, that do exactly what you’d expect:
my_hash = { one: 1, two: 2, three: 3 }
my_hash.each_key { |k| print k, " " } # ==> one two three
my_hash.each_value { |v| print v, " " } # ==> 1 2 3
What does the method string.strip do?
Returns a copy of str with leading and trailing whitespace removed.
” hello “.strip #=> “hello”
“\tgoodbye\r\n”.strip #=> “goodbye”
Which line is the correct way to write an if statement in one line using Ruby?
puts “It’s true!” if true
OR
if true puts “It’s true!”
puts “It’s true!” if true
How do you write a ternary conditional expression?
boolean ? Do this if true: Do this if false