24 Ruby tips and tricks

Peter Cooper will share more tips in his book to be released later this year. Stay tune and don’t forget to leave your email address to get updates at http://rubyreloaded.com/trickshots/

Here are some of the tips in the video.

Generate random numbers within a given range

irb(main):019:0> rand(10..20)
=> 12
irb(main):020:0> rand(10...20) # works with exclusive range
=> 16

Dump your object using awesome_print

# Install the gem first
gem install awesome_print

irb(main):001:0> require 'ap'
=> true
irb(main):002:0> ap :a => 1, :b => 'greg', :c => [1,2,3]
{
    :a => 1,
    :b => "greg",
    :c => [
        [0] 1,
        [1] 2,
        [2] 3
    ]
}
=> {:a=>1, :b=>"greg", :c=>[1, 2, 3]}

Concatenating strings

irb(main):005:0> "abc" + "def"
=> "abcdef"
irb(main):006:0> "abc".concat("def")
=> "abcdef"
irb(main):007:0> x = "abc" "def"
=> "abcdef"

Include modules in a single line

class MyClass
  include Module1, Module2, Module3
  # However, the modules are included in reverse order. Confusing eh!
end

Instance variable interpolation

irb(main):008:0> @name = "greg"
=> "greg"
irb(main):009:0> "my name is #{@name}"
=> "my name is greg"
irb(main):010:0> "my name is #@name"
=> "my name is greg"

I still prefer the use curly braces.

Syntax checking

➜  ruby -c facu.rb 
facu.rb:12: syntax error, unexpected keyword_end, expecting $end

Zipping arrays

irb(main):027:0> names = %w(fred jess john)
=> ["fred", "jess", "john"]
irb(main):028:0> ages = [38, 47,91]
=> [38, 47, 91]
irb(main):029:0> locations = %w(spain france usa)
=> ["spain", "france", "usa"]
irb(main):030:0> names.zip(ages)
=> [["fred", 38], ["jess", 47], ["john", 91]]
irb(main):031:0> names.zip(ages, locations)
=> [["fred", 38, "spain"], ["jess", 47, "france"], ["john", 91, "usa"]]

Range into arrays

irb(main):034:0> (10..20).to_a  # what I used to do
=> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
irb(main):035:0> [*10..20]
=> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Using parameter as default value

irb(main):047:0> def method(a, b=a); "#{a} #{b}"; end
=> nil
irb(main):048:0> method 1
=> "1 1"
irb(main):049:0> method 1, 2
=> "1 2"

Put regex match in a variable

irb(main):058:0> s = "Greg Moreno"
=> "Greg Moreno"
irb(main):059:0> /(?<first>\w+) (?<second>\w+)/ =~ s
=> 0
irb(main):060:0> first
=> "Greg"
irb(main):061:0> second
=> "Moreno"
About these ads
Tagged

32 thoughts on “24 Ruby tips and tricks

  1. Hi! This is my first visit to your blog! We are
    a collection of volunteers and starting a new initiative in
    a community in the same niche. Your blog provided us valuable information to work on.
    You have done a extraordinary job!

  2. Eddie says:

    I all the time used to read piece of writing in news papers but now as I am a user of internet so from now I am
    using net for content, thanks to web.

  3. It’s going to be finish of mine day, but before finish I am reading this fantastic paragraph to improve my experience.

  4. My partner and I absolutely love your blog and find almost
    all of your post’s to be precisely what I’m looking for.
    Does one offer guest writers to write content for you? I wouldn’t mind writing a post or elaborating on most of the subjects you write in relation to here. Again, awesome site!

  5. Hi to all, it’s genuinely a fastidious for me to pay a quick visit this web page, it includes precious Information.

  6. Fermin says:

    I believe that is among the such a lot vital information for me.

    And i’m happy studying your article. However should statement on few general issues, The web site taste is wonderful, the articles is truly nice : D. Excellent process, cheers

  7. Chase says:

    I wanted to thank you for this great read!! I certainly
    loved every bit of it. I have got you bookmarked to
    check out new stuff you post…

  8. Minna says:

    This is the perfect web site for anyone who would like to
    understand this topic. You understand so much its almost hard to argue with you (not that I
    personally would want to…HaHa). You certainly put a
    new spin on a topic that’s been discussed for years. Wonderful stuff, just wonderful!

  9. cast of ncis says:

    I love your blog.. very nice colors & theme.

    Did you create this website yourself or did you hire someone
    to do it for you? Plz reply as I’m looking to construct my own blog and would like to find out where u got this from. thank you

  10. My spouse and I stumbled over here from a different web page and thought I should
    check things out. I like what I see so now i am following you.
    Look forward to looking at your web page for a second time.

  11. I absolutely love your blog and find almost all of your post’s to be what precisely I’m looking for.
    Does one offer guest writers to write content available for you?

    I wouldn’t mind writing a post or elaborating on a number of the subjects you write in relation to here. Again, awesome weblog!

  12. stomach says:

    The physical activity is the premier global non-profit trade association established to lead the growth of women’s MMA, something she sees every day as an instructor for children. Benn’s entourage sabotaged Eubank’s entrance music before their bout by causing it to stop abruptly, but Eubank emerged victorious on the night he fought Antonio Margarito. Exact dates for the debut of physical activity on broadcast television. The state Of Hawaii claims that this is the important part. All ways help build your overall endurance, sprint will give you a better fighter. 5 The race comprised of a 1.

  13. Superb, what a webpage it is! This blog presents helpful
    information to us, keep it up.

  14. Hmm it seems like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly
    enjoying your blog. I too am an aspiring blog writer but I’m still new to everything. Do you have any tips for first-time blog writers? I’d genuinely appreciate it.

  15. Shane says:

    Ridiculous quest there. What occurred after?
    Thanks!

  16. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you
    an e-mail. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it expand over time.

  17. I think the admin of this web site is in fact working
    hard in support of his web site, because here every information is quality based
    information.

  18. Keith says:

    At this moment I am going to do my breakfast, after having my breakfast coming over again to read other news.

  19. Hello everyone, it’s my first pay a visit at this web site, and paragraph is in fact fruitful for me, keep up posting such content.

  20. Melina says:

    All the basics will usually be covered as well as some progressive skills according to the type of course along with the skill
    level of the operator. The good news is that training
    is supported by the employment agencies,
    and many employers also conduct forklift training on-site.
    For instance, incorporating 3- 4 tonnes of attachments to the class 1 carriages simply overburdens the trucks and turn out to be rather disadvantageous than being of any benefits.

  21. Www.Svsh.Nl says:

    Have you ever considered creating an ebnook or guest authoring on other sites?

    I havge a blog based on the same ideas you discuss and would love
    to have you share some stories/information.
    I know mmy viewers would value ylur work. If you’re even remotely interested,
    feel free to shoot me an e mail.

  22. I am regular visitor, how are you everybody?
    This post posted at this site is in fact good.

  23. Humans want the things they can’t easily have and people hate to get rejected
    specially good looking girls who aren’t used to facing rejection.
    For some reason it seems to be a common misconception that taxicab drivers will
    sleep with their clientele when they get the chance. This is no doubt one of the best ways to
    get a girl attracted to you.

  24. Howdy, I do believe your web site could possibly be having web browser compatibility issues.
    Whenever I take a look at your site in Safari, it looks fine but when
    opening in Internet Explorer, it has some overlapping issues.
    I simply wanted to provide you with a quick heads up!
    Other than that, wonderful blog!

  25. Hello, i think that i noticed you visited my web site thus i came to go back the desire?.I’m attempting to in finding things to enhance my web site!I guess its good enough to use some of your ideas!!

  26. Kellye says:

    Thank you a lot for sharing this with all people you actually recognise what you are talking approximately!
    Bookmarked. Please also consult with my website =). We will have a link alternate contract between us

  27. If you are going for most excellent contents like I do, just visit this web site all the time because it offers quality contents, thanks

  28. Rosalie says:

    Hey there! Quick question that’s completely off
    topic. Do you know how to make your site mobile friendly?
    My weblog looks weird when browsing from my apple iphone.
    I’m trying to find a theme or plugin that
    might be able to resolve this issue. If you have any suggestions, please share.
    Thank you!

  29. Shona says:

    It is not my first time to go to see this website, i am visiting this web page dailly and obtain nice facts from here daily.

  30. That is a good tip particularly to those fresh to the
    blogosphere. Short but very precise info… Appreciate your sharing this
    one. A must read article!

  31. This is really fascinating, You’re a very skilled blogger.
    I’ve joined your feed and look forward to searching for extra of your magnificent post.

    Additionally, I’ve shared your site in my social networks

  32. Dewitt says:

    The World Wide Web is an important marketing medium and to gain success in this arena
    a marketer should have well planned online marketing strategy.
    As with any online marketing activity, keep the message short, sweet and direct and be sure to include the necessary
    contact information needed to send in a referral. A skilled SEO
    campaigner knows to ease out a complex site and re-structure
    it to suit real users as well as search engines.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: