“La mejor hoja de trucos de Ruby” Código de respuesta

La mejor hoja de trucos de Ruby

array = [5,4,1,3,2]
array.sort! # = [1,2,3,4,5] – works with text and other as well.
"b" <=> "a" # = 1 – combined comparison operator. Returns 0 if first = second, 1 if first > second, -1 if first < second
array.sort! { |a, b| b <=> a } # to sort from Z to A instead of A to Z
DevLorenz02

La mejor hoja de trucos de Ruby

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)
DevLorenz02

La mejor hoja de trucos de Ruby

for i in 1...10 # ... tells ruby to exclude the last number (here 10 if we .. only then it includes the last num)
  puts i
end
DevLorenz02

La mejor hoja de trucos de Ruby

:symbol # symbol is like an ID in html. :Symbols != "Symbols"
# Symbols are often used as Hash keys or referencing method names.
# They can not be changed once created. They save memory (only one copy at a given time). Faster.
:test.to_s # converts to "test"
"test".to_sym # converts to :test
"test".intern # :test
# Symbols can be used like this as well:
my_hash = { key: "value", key2: "value" } # is equal to { :key => "value", :key2 => "value" }
DevLorenz02

La mejor hoja de trucos de Ruby

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
DevLorenz02

La mejor hoja de trucos de Ruby

class DerivedClass < BaseClass; end # if you want to end a Ruby statement without going to a new line, you can just type a semicolon.

class DerivedClass < Base
  def some_method
    super(optional args) # When you call super from inside a method, that tells Ruby to look in the superclass of the current class and find a method with the same name as the one from which super is called. If it finds it, Ruby will use the superclass' version of the method.
      # Some stuff
    end
  end
end

# Any given Ruby class can have only one superclass. Use mixins if you want to incorporate data or behavior from several classes into a single class.
DevLorenz02

La mejor hoja de trucos de Ruby

# single line comment
DevLorenz02

La mejor hoja de trucos de Ruby

things.each do |item| # for each things in things do something while storing that things in the variable item
  print “#{item}"
end
DevLorenz02

La mejor hoja de trucos de Ruby

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
DevLorenz02

La mejor hoja de trucos de Ruby

i = 1
while i < 11
  puts i
  i = i + 1
end
DevLorenz02

Respuestas similares a “La mejor hoja de trucos de Ruby”

Preguntas similares a “La mejor hoja de trucos de Ruby”

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código