user6589814 user6589814 - 1 year ago 75
Ruby Question

Ruby on Rails - Showing different code (button) every 2 user

I'm running

Rails 4.2.2
in my application. There is some part of my website that I would like to display different code/element every 2 user.

I know I can achieve this with
split gem
but its not a A/B testing and I don't want to make it complicated.

So basically it works like this:

Visit 1:

Visit 2
<h1>Welcome to our website</h1>

Visit 3:

Visit 4
<h1>Welcome to our website</h1>


Is it any way I can achieve this without 'split gem' or some sort of
A/B testing gem

Answer Source

You can achieve this with simple rand method

<% if rand(2).zero? %>
<% else %>
  <h1>Welcome to our website</h1> 
<% end %>


If you have more than 2 elements then its better to go for hash or case statement

Create a helper method

def conditional_element(option)
  hash = {
    0 => "<button>Login</button>",
    1 => "<h1>Welcome to our website</h1>",
    2 => "Some other element"


def conditional_element(option)
  case option
  when 0
  when 1
    "<h1>Welcome to our website</h1>"
  when 2
    "Some other element"

And use it in view

<%= conditional_element(rand(3)) %>

NOTE: You need to change the number in rand as per your number of elements

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download