> For the complete documentation index, see [llms.txt](https://docs.rulecube.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rulecube.com/v2.5/tutorial/use-constants-and-methods.md).

# Use Constants and Methods

## Introduction

Now that you've mastered the basics of creating a ruleset and calling it via its API, let's move on and add constants and predefined methods to sophisticate rulesets and speed up development.&#x20;

**Constants** are placeholders with a fixed value that you can use throughout a ruleset. They are comparable to `const` in JavaScript.&#x20;

**Methods** are predefined functionalities that execute a task or calculate a value. You can incorporate them into your ruleset, and they are comparable to JavaScript methods like `filter()` and `map()`. Because methods are predefined, they save you time in developing rulesets and make them more robust.

Rulecube has many methods ready to use for you and grouped them into these classes or categories:

* Global
  * Methods such as: `AGE()`, `ROUND()`, `TODAY(`)
* Finance
  * Methods such as calculating future values, annuities, etc.
* HTTP
  * Methods for getting or posting data over the web
* Mail
  * Methods for sending emails
* MongoDB
  * Methods for interacting with a MongoDB database
* PDF
  * Methods for generating PDF files
* SQL
  * Methods for interacting with a SQL database
* Statistics
  * Methods such as calculating standard deviation, variance, generating numbers from a normal distribution, etc.
* Workflow
  * Methods for working with workflow and its state
* System
  * Methods like creating alerts and entities on the fly, halting or restarting an execution, getting meta data of the current ruleset, etc.
* Array
  * These are extensions for the Javascript Array. Methods like `sum()`, `groupBy()`, `orderBy()`, and many more.
* Date
  * These are extensions for the Javascript Date. Methods like `addMonths()`, `diff()`, `isSameDay()`, and many more.

You may not know every category yet, but that's fine and will change as you work with Rulecube. In this guide, you'll focus on the **Global** category, which contain methods that might remind you of Excel functions.

You can use any method right away in your rulesets, and by the end of this tutorial, you'll know how to:

* Use constants in rulesets.
* Use methods in rulesets.
* Apply multiple rules in a ruleset.

## Use constants and methods

So far, your ruleset contained one rule, but rulesets can have multiple rules to distribute functionality logically. And each rule in a ruleset can use all the input and other ruleset components you defined. Furthermore, the output of each rule is combined in a joint output of the ruleset.

Let's create a new ruleset that calculates travel insurance costs to see how multiple rules, methods, and constants work. The ruleset will calculate the insurance costs based on travel days,  risk, and extra costs based on days and the number of electronic devices someone wants to insure. To cover this, the ruleset will have these inputs:

* `StartDate`
* `EndDate`
* `RiskCategory`
* `NumberOfItems`

And these rules and corresponding output:

* `InsuranceCosts`
* `ElectronicDeviceCosts`

The rest of the necessary information will follow as you develop the ruleset.

### Task: Create a new ruleset

1. Create a new ruleset named `Travel insurance calculator`
2. Create these inputs:

   <table><thead><tr><th width="298">Name</th><th>Type</th></tr></thead><tbody><tr><td><code>StartDate</code></td><td><code>date</code></td></tr><tr><td><code>EndDate</code></td><td><code>date</code></td></tr><tr><td><code>NumberOfItems</code></td><td><code>number</code></td></tr><tr><td><code>RiskCategory</code></td><td><code>enum</code></td></tr></tbody></table>
3. `RiskCategory` is an enum, this is a special type of string, which can only be one of a given possible values. To complete this step enter this comma-separated list in the "Possible values" field: `Normal, Medium, High.` This will also display the input as a dropdown in the Sandbox instead of a textbox.

This table defines how we're going to eventually calculate the total cost based on the `RiskCategory`.

<table><thead><tr><th width="254">RiskCategory</th><th>Costs per day</th></tr></thead><tbody><tr><td><code>Normal</code></td><td><code>0.35</code></td></tr><tr><td><code>Medium</code></td><td><code>0.45</code></td></tr><tr><td><code>High</code></td><td><code>0.55</code></td></tr></tbody></table>

### Task: Define constants

You're going to use the costs per day in a rule to calculate the insurance costs, and one way to do this is to hardcode the cost in your rule expression. Something like:

```javascript
// Normal risk
NumberOfDays * 0.35
// Medium risk
NumberOfDays * 0.45
// High risk
NumberOfDays * 0.55
```

This is one possible way of coding values, but it's much better to use constants for this purpose because you only have to define them once and can use them anywhere.&#x20;

Another advantage is that the value can be easily found and changed under Constants and you won't need to go through all your rules to find and replace it.

1. Click the **+** sign behind **Constants** from the left menu.\
   ↳ The **Constant details** page opens.
2. In the **Name** field, enter `CostsPerItemPerDay`.
3. In the **Constant type** list, select `Simple`.
4. In the **Value** field, enter `0.25`.

`CostsPerItemPerDay` applies to electronic devices such as smartphones with a value larger than 100 euros.

### Task: Apply methods and use constants

You're all set now to add the rules. In the rules, you're going to use these methods:

* `DAYDIFF` - to calculate the number of days between the start and end date of the travel insurance.
* `ROUND` - to round up the costs.

1. Create a rule named `NumberOfDays`
   1. Uncheck the checkbox under "**Output**" - as we do not want to include this in our output
   2. Add the following expression:

      ```
      DAYDIFF(StartDate, EndDate)
      ```
2. Add a rule named `ElectronicDeviceCosts`&#x20;
   1. Add the following expression:

      ```javascript
      ROUND(NumberOfDays * NumberOfItems * CostsPerItemPerDay)
      ```
   2. Note how we use another rule (`NumberOfDays`), an input (`NumberOfItems`) and a constant (`CostsPerItemPerDay`) in our expression.
3. Save the ruleset and try out your ruleset with different input values.&#x20;

### Task: Create a Constant Table and use it in a rule

To calculate the insurance costs, we could create an additional 3 constants for each risk category (`NormalRiskCostsPerDay`, `MediumRiskCostsPerDay` and `HighRiskCostsPerDay`) and use conditional logic in a rule to calculate it:

```javascript
if (RiskCategory == RiskCategoryEnum.Normal) {
    return ROUND(NumberOfDays * NormalRiskCostsPerDay);
}
if (RiskCategory == RiskCategoryEnum.Medium) {
    return ROUND(NumberOfDays * MediumRiskCostsPerDay);
}
if (RiskCategory == RiskCategoryEnum.High) {
    return ROUND(NumberOfDays * HighRiskCostsPerDay);
}
```

However, as you can see, this is quite complex, repetitive and tedious. But don't worry - there is a better approach to this that can simplify this to a **single line rule**!

1. Let's first create a new Constant named `RiskCostsPerDay`&#x20;
2. Change its Constant type from Simple to **Table**

You should now see an empty table like this:

<figure><img src="/files/nj5j8EAJKfnYCJ6RyOxY" alt=""><figcaption></figcaption></figure>

Let's fill this table with some values.

1. Click on the first cell and enter `Normal`
2. Press **Tab** to go to the value cell
3. Enter `0.35` in the value cell
4. Press `Enter` to create another row
5. Now repeat the previous steps to end up with a table that looks like this:<br>

   <figure><img src="/files/1zGkxPqGBv2GlGvrWjBX" alt=""><figcaption></figcaption></figure>

Now that we've created our table, let's use it in a rule.

1. Create a rule named `InsuranceCosts`
   1. Add the following expression:<br>

      <pre class="language-javascript"><code class="lang-javascript"><strong>ROUND(RiskCostsPerDay.get(RiskCategory) * NumberOfDays)
      </strong></code></pre>

      \
      **Explanation**\
      `RiskCostsPerDay.get()` is a method that will get a value from the constant table by **Key**.\
      \
      For example, `RiskCostsPerDay.get("Normal")` would return `0.35`.\
      \
      We're passing in the `RiskCategory` input variable instead, which is either "Normal", "Medium" or "High" as that's how we've defined its Possible values.<br>
2. Save the ruleset and try it out with different input values.&#x20;

The result of your ruleset should look something like this:

<figure><img src="/files/66F8eA0MISSn7ZEHvrV1" alt=""><figcaption></figcaption></figure>

## Extra: explore Rulecube's predefined methods

You've only seen the tip of the methods iceberg yet. To see what methods are available and explore their possibilities, follow these steps:

1. Click the question mark ![](/files/oMuvWS20uI12rmKzRofe) and select **Documentation**.\
   ↳ Your browser opens the **Language (Methods) Reference** in a new tab.
2. Open up the sections in the menu and explore the available methods.

## Recap

You now know how to use methods and constants in rulesets. And how to define multiple rules in a ruleset. Your rulesets are already getting pretty advanced, and you only need to take a few more steps before you create fully working rulesets.

## What's next?

Rulecube also lets you develop your own methods, called **functions**, that can save you a lot of repeating work and make your rules more manageable. As you'll learn in the next tutorial.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.rulecube.com/v2.5/tutorial/use-constants-and-methods.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
