Skip to content

Instantly share code, notes, and snippets.

@artemeff
Last active December 19, 2015 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artemeff/5947857 to your computer and use it in GitHub Desktop.
Save artemeff/5947857 to your computer and use it in GitHub Desktop.
Ruby tips
# string merging
"asd" "qwe" "zxc"
# => "asdqwezxc"
# separators may be a space
% sometext .size
# => 8
# fast array creation
[*0..5]
# => [0, 1, 2, 3, 4, 5]
# json pretty print
require 'json'
a = {a: [1,2,3], b: 'c'}
j a
# => {"a":[1,2,3],"b":"c"}
jj a
# =>
# {
# "a": [
# 1,
# 2,
# 3
# ],
# "b": "c"
# }
# underscore as a last result (irb)
"TEST".downcase
# => "test"
_
# => "test"
_ + _
# => "testtest"
# source path
require 'json'
method(:j).source_location
# => ["/Users/artemeff/.rbenv/versions/2.0.0-p0/lib/ruby/2.0.0/json/common.rb", 447]
# extract data to variables from regular expression
str = "Fred Flinstone: TESTBANGAHAHA"
str[/(\w+) (\w+)/]
# => "Fred Flinstone"
str[/(\w+) (\w+)/, 1]
# => "Fred"
str[/(\w+) (\w+)/, 2]
# => "Flinstone"
str[/(?<first>\w+) (?<last>\w+)/, :last]
# => "Flinstone"
$~[:first]
# => "Fred"
$~
# => #<MatchData "Fred Flinstone" first:"Fred" last:"Flinstone">
/(?<first>\w+) (?<last>\w+)/ =~ str
first
# => "Fred"
last
# => "Flinstone"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment