---
title: "Operations"
url: https://docs.zeroc.com/ice/3.8/slice/operations
language: ruby
docs_index: https://docs.zeroc.com/llms.txt
---

> For an index of every page, see [llms.txt](https://docs.zeroc.com/llms.txt).

# Operations

Programming language: Ruby. Other languages: [C++](https://docs.zeroc.com/ice/3.8/slice/operations/cpp.md), [C#](https://docs.zeroc.com/ice/3.8/slice/operations/csharp.md), [Java](https://docs.zeroc.com/ice/3.8/slice/operations/java.md), [JavaScript](https://docs.zeroc.com/ice/3.8/slice/operations/js.md), [MATLAB](https://docs.zeroc.com/ice/3.8/slice/operations/matlab.md), [PHP](https://docs.zeroc.com/ice/3.8/slice/operations/php.md), [Python](https://docs.zeroc.com/ice/3.8/slice/operations/python.md), [Swift](https://docs.zeroc.com/ice/3.8/slice/operations/swift.md).

## Operation Syntax

An operation definition has a name, a return type, and zero or more parameters.

For example:

```slice
module M
{
    struct TimeOfDay
    {
        short hour;         // 0 - 23
        short minute;       // 0 - 59
        short second;       // 0 - 59
    }

    interface Clock
    {
        TimeOfDay getTime();
        void setTime(TimeOfDay time);
    }
}
```

An operation that returns no value, such as `setTime`, declares `void` as its return type.

Parameters are input parameters by default: their values go from the client to the server. An output parameter, marked with the `out` keyword, carries a value from the server back to the client. An operation can have several input and output parameters, and its output parameters must follow its input parameters:

```slice
module M
{
    interface CircadianRhythm
    {
        void setSleepPeriod(TimeOfDay startTime, TimeOfDay stopTime);
        void getSleepPeriod(out TimeOfDay startTime, out TimeOfDay stopTime);
        void changeSleepPeriod(
            TimeOfDay startTime,
            TimeOfDay stopTime,
            out TimeOfDay prevStartTime,
            out TimeOfDay prevStopTime);
    }
}
```

Each parameter must have a name, and a parameter cannot be both an input and an output parameter.

## Optional Parameters and Return Values

An operation's return value and parameters may be declared as optional to indicate that a program can leave their values unset. Parameters not declared as optional are known as *required* parameters. In the discussion below, we use *parameter* to refer to input parameters, output parameters, and return values.

A unique, non-negative integer *tag* must be assigned to each optional parameter:

```slice
optional(3) bool example(optional(2) string name, out optional(1) int value);
```

The scope of a tag is limited to its operation and has no effect on other operations. You can assign tags in any order.

An optional parameter cannot have a class type, or a constructed type that holds a class type.

An operation's signature can include any combination of required and optional parameters, but output parameters still must follow input parameters:

```slice
bool example(
    string name,
    optional(3) string referrer,
    out optional(1) string promo,
    out int id);
```

Language mappings specify an API for passing optional parameters and testing whether a parameter is present.

## Exception Specifications

An operation lists the user exceptions it can throw in its [exception specification](https://docs.zeroc.com/ice/3.8/slice/exceptions/ruby.md#exception-specification-in-operations), a `throws` clause.

## Overloading Operations

Slice does not support overloading: operations in the same interface must have different names, regardless of the type and number of their parameters. A request identifies the operation it invokes by name only.

## Idempotent Operations

An operation is idempotent when calling it several times with the same arguments has the same effect as calling it once. Operations that do not modify the state of the object, such as `getTime` in the `Clock` interface, are idempotent; so is `setTime`, even though it modifies the state. You mark such operations with the `idempotent` keyword:

```slice
interface Clock
{
    idempotent TimeOfDay getTime();
    idempotent void setTime(TimeOfDay time);
}
```

The `idempotent` keyword makes this property part of the contract: the implementation must keep the operation idempotent, and callers can rely on it. Ice relies on it to retry invocations it would not retry otherwise; see [Automatic Retries](https://docs.zeroc.com/ice/3.8/runtime/invocation/automatic-retries/ruby.md).

## Client-Side Mapping for Operations

### Mapping for Operations

As we saw in the [Client-Side Ruby Mapping for Interfaces](https://docs.zeroc.com/ice/3.8/slice/interfaces/ruby.md#client-side-mapping-for-interfaces), for each operation on an interface, the generated proxy class contains a method with the same name. To invoke an operation, you call this method on the proxy. For example, let’s take the generated code from the [greeter example](https://docs.zeroc.com/ice/3.8/greeter-example/defining-the-greeter-interface-in-slice/ruby.md):

```slice
module VisitorCenter
{
    interface Greeter
    {
        string greet(string name);
    }
}
```

The proxy class generated from the `Greeter` interface, after removing extra details, is as follows:

```ruby
module ::VisitorCenter
    module GreeterPrx_mixin
        def greet(name, context=nil)
            GreeterPrx_mixin::OP_greet.invoke(self, [name], context)
        end
    end

    class GreeterPrx < Ice::ObjectPrx
        include GreeterPrx_mixin
    end

    # ...
end
```

Given a proxy to an object of type `Greeter`, the client can invoke the `greet` operation as follows:

```ruby
greeter = VisitorCenter::GreeterPrx.new(
    communicator, "greeter:tcp -h localhost -p 4061")

greeting = greeter.greet("Alice")  # Get name via RPC
```

### Exception Handling

Any operation invocation may raise a [runtime exception](https://docs.zeroc.com/ice/3.8/runtime/local-and-dispatch-exceptions/ruby.md) and, if the operation has an exception specification, may also raise [user exceptions](https://docs.zeroc.com/ice/3.8/runtime/local-and-dispatch-exceptions/ruby.md). Suppose we have the following simple interface:

```slice
exception Tantrum
{
    string reason;
}

interface Child
{
    void askToCleanUp() throws Tantrum;
}
```

Slice exceptions are raised as Ruby exceptions, so you can simply enclose one or more operation invocations in a `begin-rescue` block:

```ruby
child = ...        # Get child proxy...

begin
    child.askToCleanUp()
rescue Tantrum => t
    puts "The child says: #{t.reason}"
end
```

## Mapping for Parameters and Return Values

### In Parameters

An in parameter maps to a Ruby method argument, and an invocation does not modify the arguments you pass.

Here is an interface with operations that pass parameters of various types from client to server:

```slice
struct NumberAndString
{
    int x;
    string str;
}

sequence<string> StringSeq;

dictionary<long, StringSeq> StringTable;

interface ClientToServer
{
    void op1(int i, float f, bool b, string s);
    void op2(NumberAndString ns, StringSeq ss, StringTable st);
    void op3(ClientToServer* proxy);
}
```

The Slice compiler generates the following proxy for this definition:

```ruby
module ClientToServerPrx_mixin
  def op1(i, f, b, s, context=nil)
      # ...
  end

  def op2(ns, ss, st, context=nil)
      # ...
  end

  def op3(proxy, context=nil)
      # ...
  end
end

class ClientToServerPrx < Ice::ObjectPrx
    include ClientToServerPrx_mixin
end
```

Given a proxy to a `ClientToServer` interface, the client code can pass parameters as in the following example:

```ruby
p = ...                                 # Get proxy...

p.op1(42, 3.14, true, "Hello world!")   # Pass simple literals

i = 42
f = 3.14
b = true
s = "Hello world!"
p.op1(i, f, b, s)                       # Pass simple variables

ns = NumberAndString.new()
ns.x = 42
ns.str = "The Answer"
ss = [ "Hello world!" ]
st = {}
st[0] = ss
p.op2(ns, ss, st)                       # Pass complex variables

p.op3(p)                                # Pass proxy
```

### Out Parameters and Return Values

The return value of a mapped method depends on how many values the corresponding Slice operation returns, including out parameters and a non-`void` return value:

- **Zero values** The corresponding Ruby method returns `nil`.
- **One value** The client receives a single return value, regardless of whether the Slice definition of the operation declared it as a return value or as an out parameter.
- **Two or more values** The client receives them in the form of a *result array*. A non-`void` return value, if any, is always the first element in the result array, followed by the `out` parameters in the order of declaration.

Here again are the same Slice definitions we saw earlier, but this time with all parameters being passed in the `out` direction:

```slice
struct NumberAndString
{
    int x;
    string str;
}

sequence<string> StringSeq;
dictionary<long, StringSeq> StringTable;

interface ServerToClient
{
    int op1(out float f, out bool b, out string s);

    void op2(out NumberAndString ns,
             out StringSeq ss,
             out StringTable st);

    void op3(out ServerToClient* proxy);
}
```

The generated proxy methods have the following signatures:

```ruby
def op1(context=nil)
def op2(context=nil)
def op3(context=nil)
```

Given a proxy to a `ServerToClient` interface, the client code can receive the results as in the following example:

```ruby
p = ...              # Get proxy...
i, f, b, s = p.op1()
ns, ss, st = p.op2()
stcp = p.op3()
```

The operations have no `in` parameters, therefore no arguments are passed to the proxy methods. Since `op1` and `op2` return multiple values, their result arrays are unpacked into separate values, whereas the return value of `op3` requires no unpacking.

### Parameter Type Mismatches

Ice validates the arguments to a proxy invocation at runtime and reports any type mismatches as a `TypeError` exception.

### Nil Parameters

Slice sequences and dictionaries have no null value. When you pass `nil` for a sequence or dictionary, whether as a parameter, a field, or a sequence element, Ice sends an empty sequence or dictionary. For an [optional](#optional-parameters) parameter or field, `nil` instead leaves the value unset.

### Optional Parameters

[Optional parameters](#optional-parameters-and-return-values) use the same mapping as required parameters. The only difference is that `nil` can be passed as the value of an optional parameter or return value to leave it unset. Consider the following operation:

```slice
optional(1) int execute(optional(2) string p, out optional(3) float value);
```

A client can invoke this operation as shown below:

```ruby
i, v = proxy.execute("--file log.txt")
i, v = proxy.execute(nil)

if v != nil
    puts "value = " + v.to_s
end
```

Check an optional parameter against `nil` before using its value.
