Home > Enterprise >  How to run a block of code only for the first element of a array in Ruby-on-rails?
How to run a block of code only for the first element of a array in Ruby-on-rails?

Time:03-02

I want to run a block of code only for the first element of a array. I have the following code as of now

$data = YAML.load_file(yml_file_to_load)
    @Alarms = $data['Alarms']
    @Alarms.each do |alarm|
    
          describe "Test code is going start from here", :test do

This particular code run the block for every element in the array @Alarms. I want the code to run only for first element that is the code has to run only once.

Note that I also want to preserve the value of alarm variable inside the block. Here the variable should contain first element of array.

CodePudding user response:

When you only want to test the first element of the array then just assign the element to a variable, for example like this:

before do
  data = YAML.load_file(yml_file_to_load)
  @alarm = data['Alarms'][0]
end

describe "Test code is going start from here", :test do
  # use @alarm in the test

CodePudding user response:

You can use Object#tap to yield any object to a block:

$data = YAML.load_file(yml_file_to_load) # Why are you using a global?
@alarms = $data['alarms'] # variables should be snakecase
@alarms.first.tap do |alarm|
  # ...
end

tap returns the original object. So its useful when you're only interested in the side effects. If you want to use the return value of the block use then:

result = @alarms.first.then do |alarm|
  # ...
end
  • Related