1. Truthiness of objects in Ruby
Only objects false and nil equates to false. Every other object like say 1, 0, "" are all evaluated to be true.
2. Use break in infinite loops
loop do monk.meditate break if monk.nirvana? end3. Append to an array, use << operator
[1, 2, 3, 4, 5] << 'woot' [1, 2, 3, 4, 5, "woot"]4. Filter elements of an array, use 'select'
names = ['rock', 'paper', 'scissors', 'lizard', 'spock'] names.select { |word| word.length > 5 }5. Delete elements of an array, use 'delete_if'
[1,2,3,4,5,6,7,8,9].delete_if { |i| i % 2 == 0 }6. Methods are themselves objects, and responds using 'call'
next_method_object = 1.method("next") puts next_method_object.call7. Beware of shallow object copies, to do a deep copy use Marshal
new_job = Marshal.load(Marshal.dump(job))8. Use heredoc for convenient multiline strings. The dash ignores spaces before placeholder. The gsub takes care of removing spaces at beginning of each line.
def long_message puts <<-EOT.gsub(/^\s*/, '') Here goes a very long message... Sincerely, Dr. Foobear EOT end7. Use 'send' when testing private methods
# obj.send(:method_name, args) @parser.send(:running?, test_strings)
No comments:
Post a Comment