Random Ruby Tips and Tricks

#64 Random Ruby Tips and Tricks
1/22/2017

Summary

A collection of different Ruby tips and tricks. Hope you find some of them useful!
12
ruby tricks tips

Summary

irbdef my_method(variable, *array, **json)
  return variable, array, json
end

my_method(1)
# => [1, [], {}]

my_method(1, 2, 3, 4)
# => [1, [2, 3, 4], {}]

my_method(1, 2, 3, 4, a: 5, b: 6)
# => [1, [2, 3, 4], {:a=>5, :b=>6}]
irbstuff = 1
stuff_arr = [1, 2, 3]

[*stuff].each { |s| s }
[*stuff_arr].each { |s| s }

# Careful!

a = { :name => "DK", :age => 30 }
[a]                                  # => [{:name => "DK", :age => 30}]
[*a]                                 # => [[:name, "DK"], [:age, 30]]
irba
# => nil

a ||= 1
# => a = 1

a = a || b # incorrect
a || a = b # correct

string = nil
string &&= string + "suffix"
# string is still nil

string = 'some value '
string &&= string + "suffix"
# => some value suffix
irbmoney = 42.5
"%.2f" % money
# => "42.50"

"%0.2f" % Math::PI  # => "3.14"
irb#Dependency Ruby 2.3.0

current_user.try(:full_name)
current_user&.full_name
irbdef is_odd(x)
  if x % 2 == 0
    return false
  else
    return true
  end
end

def is_odd(x)
  x % 2 == 0 ? false : true
end

def is_odd(x)
  x % 2 != 0
end
irbstrs = ['foo', 'bar', 'baz']
caps = strs.map { |str| str.upcase }
caps = strs.map(&:upcase)

cars = %w[beetle volt camry]
=> ["beetle", "volt", "camry"]

cars.sort_by { |car| car.size }
=> ["volt", "camry", "beetle"]

cars.sort_by(&:size)
=> ["volt", "camry", "beetle"]
irbfood = %w( tacos milk eggs )
food.map(&:object_id)       # [x1, y1, z1]
food.clone.map(&:object_id) # [x1, y1, z1]

# Using the Marshal class, which is normally used for serialization, you can create a ‘deep copy’ of an object.

def deep_copy(obj)
  Marshal.load(Marshal.dump(obj))
end

deep_copy(food).map(&:object_id) # [x2, y2, z2]
irbArray.new(10)
# => [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
Array.new(10) { rand 100 }
# => [77, 34, 79, 43, 70, 86, 43, 96, 18, 3]
irbImpression.select(:id, :impressionable_type, :impressionable_id).last(10)
  Impression Load (0.3ms)  SELECT  `impressions`.`id`, `impressions`.`impressionable_type`, `impressions`.`impressionable_id` FROM `impressions` ORDER BY `impressions`.`id` DESC LIMIT 10
# => [#, #, #, , #, #, , #, #, ]

Impression.select(:id, :impressionable_type, :impressionable_id).last(10);
# =>  Impression Load (0.3ms)  SELECT  `impressions`.`id`, `impressions`.`impressionable_type`, `impressions`.`impressionable_id` FROM `impressions` ORDER BY `impressions`.`id` DESC LIMIT 10

Impression.select(:id, :impressionable_type, :impressionable_id).last(10);
# =>  Impression Load (0.3ms)  SELECT  `impressions`.`id`, `impressions`.`impressionable_type`, `impressions`.`impressionable_id` FROM `impressions` ORDER BY `impressions`.`id` DESC LIMIT 10
irbitems = { :tacos => 12, :eggs => 3 }
# => items = {:tacos=>12, :oranges=>3}

items.fetch(:tacos)
# => 12

items.fetch(:bananas) { |key| "We don't carry #{key}!"}
# => We don't carry bananas!

items.fetch(:eggs)
# => 3
irb100.to_s(2)
# => "1100100"

"1100100".to_i(2)
# => 100
7800933?v=3&s=64
digaev said 4 months ago:

Nice tricks, knew most of them, but somehow I missed `current_user&.full_name `. Thanks!

319081?v=3&s=64
danielpclark said 4 months ago:

Three of these were new to me.  &&= and fetch piping in the parameter into the block are possibly useful to me.  I just need to think of a use case in my day to day coding.

430345?v=3&s=64
davearonson said 4 months ago:

Be careful when using ||= with Boolean values.  ||= will set something not only if it's nil, but also if it's literally false, i.e., the one object named false, of class FalseClass.  In short it will set it if it's "falsey".

That part also reminded me of some strange code I encountered recently: "if status == status = 1 || status = 2 || status = 3".  See http://blog.codosaur.us/2016/11/x-x-wtf.html for a writeup of what that was probably meant to do, and what it really did.

00000000000000000000000000000000?d=mm&f=y&s=64
Scudelletti said 4 months ago:

It's always nice to see tricks. 

Some time ago I did a Ruby Tips and Tricks presentation, maybe it can give you more ideas for the part II.

http://www.slideshare.net/Scudelletti/ruby-tips-andtricks

About `fetch` you can also pass the default value as the second argument instead of a block.
`{a: 1}.fetch(:b, 200)`

Nice video!

796584?v=3&s=64
kamil89 said 3 months ago:

There's also a trick with passing method instances:

def say_hello(name)
  puts "Hello #{name}"
end
names = ["James", "Jacob", "Jack"]

One way to call say_hello with args from array is:

names.map { |name| say_hello(name) }

And the shortened version with method instance would be:

names.map(&method(:say_hello))

Login to Comment