Using CheatSheets To Apply Best Practices

Ruby Free CheatSheet

Ruby Free CheatSheet

1.1 Summary

Name Comment
Check syntax ruby -c my.rb
Generate random key r =, r.rand(10...42)
Install ruby 2.4 GitHub: Ubuntu install ruby 2.4
Install package with specific version gem install rubocop -v "0.44.1"
Install package with a range of versions gem install rails -v "~>4.0.0"
Install package with a range of versions gem install rails -v ">3.1, <4.1"
Get RubyGem env gem env
Check whether variable is nil if value.nil?
Run system command system("commandhere")
Run bash command stdin, stdout, stderr = Open3.popen3('ls .')

1.2 List

Name Comment
Check existence [‘Cat’, ‘Dog’, ‘Bird’].include? ‘Dog’
Find item l1.find_index(x)
Remove item from list l1.delete_at(2)
Remove duplicate entries [1,2,2,1,4,4,5,6,7,8,5,6].uniq
Deep copy a list l1=l.dup

1.3 String

Name Comment
Substring string[1..3]
Search substring “option=name=bob”.index(“name”)
Replace “Welcome to PHP Essentials!”.gsub(“PHP”, “Ruby”)
Remove trailing comma “ab;123;”.chomp(“;”)
Strip whitespace host = host.strip()

1.4 Integer

Name Comment

1.5 Conversion

Name Comment
Convert string to int “14”.toi, “1,112”.delete(‘,’).toi
Round float to 2 digits (5.65235534).round(2)
Format datetime puts time.strftime("%Y-%m-%d %H:%M:%S")

1.6 Dict & Set

Name Comment

1.7 File

Name Comment
Check whether directory exist'xxx")
Check whether files exist File.file?('hello.rb')
Read file to string contents ='filename')
  • Write to file
# append'/tmp/test.txt', 'a') { |file| file.write("your text\n") }

# overwrite'/tmp/test.txt', 'w') { |file| file.write("your text\n") }

1.8 Code Snippets

  • Get ip from eth0
ruby -rsocket -e 'p IPSocket.getaddress(Socket.gethostname)'

require 'socket'

  • Get hostname
require 'socket'
hostname = Socket.gethostbyname(Socket.gethostname).first

  • Get hostname from ip
  def get_hostname_by_ip(ip_address)
    require 'resolv'
    dns =

    hostname = ip_address
      hostname = dns.getname(ip_address)
      # TODO: show error message
      puts "ERROR: Exception"
    return hostname

1.9 More Resources

License: Code is licensed under MIT License.


Leave a Reply

Your email address will not be published. Required fields are marked *