This post originated from an RSS feed registered with Ruby Buzz
by Jan Lelis.
Original Post: Introducing Ruby Zucker - a new syntactical sugar gem
Feed Title: rbJ*_*L.net
Feed URL: http://feeds.feedburner.com/rbJL
Feed Description: Hi, I am a fan of Ruby and like to explore it and the world around ;).
So I started this blog, where I am publishing code snippets, tutorials for beginners as well as general thoughts about Ruby, the web or programming in general.
Zucker is a collection of lightweight scripts (cubes) that make Ruby even more beautiful: rubyzucker.info
Setup
Install the gem with: gem install zucker
Then, you can start using it by loading it into your code with: require 'zucker/all'
Cubes
Some snippets of older blog posts are included in this gem: egonil, to_proc-methods and the method_list. This blog post demonstrates some of the other features. It’s also available as slides from the rug-b talk.
# iterate basically does the same thing as each, but with two differences:# It feels more like a control structure and it allows easy iteration over# multiple objects.iterate[1,2],[3,4,5]do|e,f|puts"#{e},#{f}"end# outputs# 1,3# 2,4# ,5
# Regex.union is a nice features added in Ruby 1.9. You can pass Regexps or Strings# which get merged into one Regexp. Zucker adds a more intuitive syntax.# instead ofRegexp.union/Ruby\d/,/test/i,"cheat"# you can write/Ruby\d/|/test/i|"cheat"# it creates a Regexp similar to:# /(Ruby\d|[tT][eE][sS][tT]|cheat)/
# Often, you have to write boilerplate code for assigning instance varialbles like# this one:def initialize(variable1,variable2)@variable1,@variable2=variable1,variable2end# You can change it todef initialize(variable1,variable2)instance_variables_frombinding# assigns @variable1 and @variable2end# Another way of usage is to pass an hash as argument:params={:c=>3,:d=>4}instance_variables_fromparams# # assigns @c and @d
# Sometimes, you do not care if you get a String or Symbol as input - but often,# you need to choose one later in your code. A concise possibility for this# conversion is using the unary operators String#-@ and Symbol#+@+:symbol# => 'symbol' (1.9)now={:rugb=>true,:whyday=>false}input='rugb'now[-input]# => true