1. Deep copy When you copy an object that contains other objects, like an Array, only a reference to these objects is copied. You can see that in action here:
|
1 2 3 |
food = %w( bread milk orange ) food.map(&:object_id) # [35401044, 35401020, 35400996] food.clone.map(&:object_id) # [35401044, 35401020, 35400996] |
Using the Marshal class, which is normally used for serialization, you can create a ‘deep copy’ of an object.
|
1 2 3 |
def deep_copy(obj) Marshal.load(Marshal.dump(obj)) end |
The results:
|
1 |
deep_copy(food).map(&:object_id) # [42975648, 42975624, 42975612] |
2. […]
Understanding Blocks Blocks are very prevalent in Ruby, you can think of them as little anonymous functions that can be passed into methods. Blocks are enclosed in a do / end statement or between brackets {}, and they can have multiple arguments. The argument names are defined between two pipe | characters. If you have […]
Arrays are a fundamental data structure that stores data in memory. In Ruby you can store anything in an array, from strings to integers and even other arrays. The elements in an array are accessed using their index, which starts at 0. This is what an array containing the words “cat”, “dog” and “tiger” would […]
If you ever tried to write a scrapping tool you probably had to deal with parsing html. This task can be a bit difficult if you don’t have the right tools. Ruby has this wonderful library called Nokogiri, which makes html parsing a walk in the park. Let’s see some examples. First install the nokogiri […]
Let’s talk about how you can format strings in ruby. Why would you want to format a string? Well, you may want to do things like have a leading zero even if the number is under 10 (example: 01, 02, 03…), or have some console output nicely formatted in columns. In other languages you can […]
© 2016 Black Bytes. All rights reserved.
Delicately crafted using Franz Josef theme and WordPress.