21 comments
Thanks, Jesus!
I like your blog π
Just want to add a little detail to trick 10: I think that just putting ‘;’ after any ruby code will suppress the output.
RestClient.get('blackbytes.info');
You are right! Thanks for pointing that out π
But in (my) irb, just leaving a trailing ;
will not execute the expression. It is now waiting for another expression on a new line. I usually append ‘;nil’.
Maybe there is another dependency (readline?) in play.
Thank you so much, Jesus, it’s really kind of you to share such useful tricks! Cheers
Thank you. I’m glad you found them useful π
Good article.There are some tricks i have not seen before.
Thanks for reading π
Good Tricks
Thanks for reading!
My inner troll politely asks, “What happens when you deep clone objects which are actually just wrappers over external resources, i.e. sockets, file handles, db connections, etc.?”
That’s an interesting question π
I just ran a quick test and the answer is simple: Ruby won’t let you do it.
I tried with a socket and I get: TypeError: can't dump TCPSocket
.
Adding “;” to the end of the line will also let you create a function on a single line. IE: def hello_world; puts “Hi”; end
For #1, for a simple string array, we could also use the following.
food.map(&:clone).map(&:object_id)
May be, if the objects are deep by multiple levels, marshaling could be a way.
Calling a lambda with triple equal doesn’t make a whole lot of sense to me π
-> { "wat" }.===
This is a thing because case statements use ===
.
You can read more about that in this post.
Trick #3 incorrectly states “This will generate an array with 10 random numbers which are between 0 and 300.”
Actually rand(max) generates a number less than max: 0 <= n < max
http://ruby-doc.org/core-2.3.0_preview1/Random.html#method-i-rand
You’re right. I have corrected the problem, thanks for letting us know.
Here’s another one for your list… a little gem which uses Fiddle to access an otherwise internal-only part of Ruby itself to access the bindings of any caller of a function. If a calls b, which calls c, which calls d… then the ‘bindings’ gem will allow the d method to access variables defined in c, b, or a. The code is tiny and has been extremely helpful for us!
Check it out at: https://github.com/shreeve/bindings
Thank you π
“Bonus: The maximum Fixnum is 1073741823, after that you get a Bignum object.”
Only for 32-bit systems.