/RethinkDB Ruby

ReQL command: do

Command syntax

any.do(function) → any
r.do([args]*, function) → any
any.do(expr) → any
r.do([args]*, expr) → any


Call an anonymous function using return values from other ReQL commands or queries as arguments.

The last argument to do (or, in some forms, the only argument) is an expression or an anonymous function which receives values from either the previous arguments or from prefixed commands chained before do. The do command is essentially a single-element map, letting you map a function over just one document. This allows you to bind a query result to a local variable within the scope of do, letting you compute the result just once and reuse it in a complex expression or in a series of ReQL commands.

Arguments passed to the do function must be basic data types, and cannot be streams or selections. (Read about ReQL data types.) While the arguments will all be evaluated before the function is executed, they may be evaluated in any order, so their values should not be dependent on one another. The type of do’s result is the type of the value returned from the function or last expression.

Example: Compute a golfer’s net score for a game.

r.table('players').get('f19b5f16-ef14-468f-bd48-e194761df255').do { |player|
    player['gross_score'] - player['course_handicap']

Example: Return the best scoring player in a two-player golf match.

r.do(r.table('players').get(id1), r.table('players').get(id2)) { |player1, player2|
    r.branch(player1['gross_score'].lt(player2['gross_score']), player1, player2)

Note that branch, the ReQL conditional command, must be used instead of if. See the branch documentation for more.

Example: Take different actions based on the result of a ReQL insert command.

new_data = {
    :id => 100,
    :name => 'Agatha',
    :gross_score => 57,
    :course_handicap => 4
r.table('players').insert(new_data).do{ |doc|
        r.table('log').insert({:time => r.now(), :response => doc, :result => 'ok'}),
        r.table('log').insert({:time => r.now(), :response => doc, :result => 'error'})

Related commands

Get more help

Couldn't find what you were looking for?

© RethinkDB contributors
Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.