0

I would like to sort Ruby Array by key in variable, but I don't know how.

Situation

my_arr.sort_by {|record| [record.year]}

Will sort by a year of the record. But I want to sort by author, label, etc. And this sort type is stored in a variable like a String. So I need to evaluate the filter like

my_arr.sort_by {|record| [record."something_in_the_var"]}

Of course, I have fixed filters. But still figuring out how to do it properly.

Thanks for tips

0

2 Answers 2

1

This is what send does

str = "label"
arr.sort_by{|rec| rec.send(str) }

send is defined on BasicObject, so every object has it.

Sign up to request clarification or add additional context in comments.

Comments

1

you can use something like

sort_by_this = "label"

my_arr.sort_by {|record| [record[sort_by_this]]}

1 Comment

I tried this, I got NoMethodError: undefined method []'` :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.