0

Example java code is below if I have a class Movie
In java I will create its array by writing below code
Movie[] a = new Movie[4];

but how I can do it in rails So that when I check it on the console

#> a.type
#> "Movie"

Reather than

#> ActiveRecord::Relation
1
  • Please learn how to use SO formatting, don't use HTML tags again. Commented Jul 23, 2013 at 7:22

2 Answers 2

1

You just create a class by inherited from Array like below,

class MyArray < Array
 #Add you custom methods
end

my_array = MyArray.new([1,2,3,4,5]) or

my_array = MyArray.new
my_array[0] = 1
my_array[1] = 2

That enough for basic customization of array data structure.

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

1 Comment

Movie is my model class
1

Literal translation would be

a = (1..4).map { Movie.new }

or (in Rails)

a = (1..4).map { Movie.create! }

but you normally shouldn't need to do it, since unlike in Java, you don't have limited-size arrays in Ruby.

Also, the type of that would then be Array (or rather its class; basic Ruby objects don't have type); the type of an element of that, a[0] for example, would be a Movie.

In the end, not quite sure what you're asking here...

Comments

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.