0

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.

3 Answers3

1

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?

Community
  • 1
  • 1
Godwin
  • 9,739
  • 6
  • 40
  • 58
1

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'

bkunzi01
  • 4,504
  • 1
  • 18
  • 25
1

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.

JBM
  • 11
  • 1