Reputation: 130
Lately I was developing some code using Backbone.js and Coffeescript, and got pretty much used to Coffeescripts built in methods to access stuff passed as objects:
{ firstname, lastname, @email } = options
Which is equivalent of:
firstname = options.firstname
lastname = options.lastname
@email = options.email
Is there any built in Ruby syntax for achieving same behaviour on Ruby's hashes?
What I've managed to achieve so far is this:
firstname, lastname, @email = params.values_at(:firstname, :lastname, :email)
But it isn't a 1:1 solution of problem.
JS generated by Coffeescript:
var firstname, lastname;
firstname = options.firstname, lastname = options.lastname, this.email = options.email;
Upvotes: 1
Views: 238
Reputation: 35483
Ruby doesn't have any built-in solution; your solution is the right way to do it.
firstname, lastname, @email = params.values_at(:firstname, :lastname, :email)
If you happen to know the hash is an ordered hash, and contains just the values you want, and in the order you want, then you can get all the values like this:
# Suppose params = {
# firstname: …,
# lastname: …,
# email: ….
# }
firstname, lastname, @email = params.values
As a general hint, if you happen to know the hash is an ordered hash, and contains more entries than the values you want, yet the values are in the order you want, then you can get all the values and skip the ones you don't care about. Use the "useless" underscore variable as a placeholder as many times as you want, to skip an omittable value:
# Suppose params = {
# firstname: …,
# middlename: …,
# lastname: …,
# bithdate: …,
# email: …,
# whatever: …
# }
firstname, _, lastname, _, @email, _ = params.values
Upvotes: 2