Created
October 29, 2021 14:25
-
-
Save RuslanSevrukov/2d76574fcd5240f2630961852f1ef56b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Is the line of code below valid Ruby code? If so, what does it do? Explain your answer. | |
-> (a) {puts a}["Hello world"] | |
# #Write a function that sorts the keys in a hash by the length of the key as a string; | |
#should return ["abc", "4567", "another_key"] | |
hsh = { abc: 'hello', 'another_key' => 123, 4567 => 'third' } | |
hsh.sort_by { |key| key.to_s.length } | |
# #Can you call a private method outside a Ruby class using its object? | |
class Test | |
def foo | |
p "Public method" | |
end | |
private | |
def method | |
p "I am a private method" | |
end | |
end | |
test = Test.new | |
test.send(:method) | |
# #Find duplicates | |
arr = ["A", "B", "C", "B", "A"] | |
counted_items = Hash.new(0) | |
arr.each { |elem| counted_items[elem] += 1} | |
#What’s the following program going to print? | |
x = 1 | |
class MyClass | |
y = 2 | |
def foo | |
z = 4 | |
y ||= 0 | |
puts z + y | |
end | |
define_method :bar do |x| | |
z = 5 | |
y ||= 0 | |
puts z + y + x | |
end | |
end | |
my_class = MyClass.new | |
my_class.foo #=> 6 | |
my_class.bar(10) #=> 17 | |
my_class.bar #=> Error | |
#Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment