Avada Kedavra
Avada Kedavra

Reputation: 53

How can I continues map function after if statement in Rails?

This is my code:

jobs.map do |record|
  [
    record.id,
    record.jobtitle,
    record.date,
    if (record.expired) then
      "expired"
    else
      "available"
    end
    ,
    record.views_count
  ]

but it show error: syntax error, unexpected ',', expecting ']' How can I do? Thanks for any help because i'm beginer.

Upvotes: 0

Views: 828

Answers (3)

JBM
JBM

Reputation: 11

I noticed this from Godwin's response, all you need is the brackets.

jobs.map do |record|
  [
    record.id,
    record.jobtitle,
    record.date,
    (if (record.expired) then
      "expired"
    else
      "available"
    end)
    ,
    record.views_count
  ]

Worked for me, hope that helps.

Upvotes: 1

bkunzi01
bkunzi01

Reputation: 4561

Remove the 'then' in your if/else statement. Using 'then' is more for clarity on one-liner if statements. Also, move that if/else statement outside of the array. So:

jobs.map do |record|
    if (record.expired)
      x = "expired"
    else
      x = "available"
    end
  [
    record.id,
    record.jobtitle,
    record.date,
    x,
    record.views_count
  ]

If you like one-liners you can use the ternary operator ? for if/else such as: record.expired ? x='expired' : x='available'

Upvotes: 1

Godwin
Godwin

Reputation: 9907

You could use a ternary statement instead:

jobs.map do |record|
  [
    record.id,
    record.jobtitle,
    record.date,
    (record.expired ? "expired" : "available"),
    record.views_count
  ]

How do I use the conditional operator (? :) in Ruby?

Upvotes: 1

Related Questions