Answers for "best ruby cheat sheet"

1

best ruby cheat sheet

def greeting(hello, *names) # *name is a splat argument, takes several parameters passed in an array
  return "#{hello}, #{names}"
end

start = greeting("Hi", "Justin", "Maria", "Herbert") # call a method by name

def name(variable=default)
  ### The last line in here get's returned by default
end
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

hash = { "key1" => "value1", "key2" => "value2" } # same as objects in JavaScript
hash = { key1: "value1", key2: "value2" } # the same hash using symbols instead of strings
my_hash = Hash.new # same as my_hash = {} – set a new key like so: pets["Stevie"] = "cat"
pets["key1"] # value1
pets["Stevie"] # cat
my_hash = Hash.new("default value")
hash.select{ |key, value| value > 3 } # selects all keys in hash that have a value greater than 3
hash.each_key { |k| print k, " " } # ==> key1 key2
hash.each_value { |v| print v } # ==> value1value2

my_hash.each_value { |v| print v, " " }
# ==> 1 2 3
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

=begin
Bla
Multyline comment
=end
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

for i in 1..5
  next if i % 2 == 0 # If the remainder of i / 2 is zero, we go to the next iteration of the loop.
  print i
end
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

unless false # unless checks if the statement is false (opposite to if).
puts “I’m here”
else
puts “not here”
end
# or
puts "not printed" unless true
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

i = 0
loop do
  i += 1
  print "I'm currently number #{i}” # a way to have ruby code in a string
  break if i > 5
end
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

"Hello".length # 5
"Hello".reverse # “olleH”
"Hello".upcase # “HELLO”
"Hello".downcase # “hello”
"hello".capitalize # “Hello”
"Hello".include? "i" # equals to false because there is no i in Hello
"Hello".gsub!(/e/, "o") # Hollo
"1".to_i # transform string to integer –– 1
"test".to_sym # converts to :test
"test".intern # :test
:test.to_s # converts to "test"
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

10.times do
  print “this text will appear 10 times”
end
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

i = 0
until i == 6
  puts i
  i += 1
end
Posted by: Guest on January-04-2021
0

best ruby cheat sheet

my_array = [a,b,c,d,e]
my_array[1] # b
my_array[2..-1] # c , d , e
multi_d = [[0,1],[0,1]]
[1, 2, 3] << 4 # [1, 2, 3, 4] same as [1, 2, 3].push(4)
Posted by: Guest on January-04-2021

Browse Popular Code Answers by Language