Reputation: 16521
I am trying out JRuby, and I was trying to figure out how to use Java's double brace initialization. However, it is not that apparent how the syntax would be.
To keep this example simple, the below Java code would create a list containing an element:
List<String> foo = new ArrayList<String>() {{
add("bar");
}};
Is this possible in JRuby, and if so, how?
ArrayList.new {{}}
doesn't make sense and results in the error: odd number list for Hash.puts ArrayList.new({{}})
.
Upvotes: 1
Views: 360
Reputation: 16521
While not a direct answer to the question, am I adding this because this is a convenient way of having some logic determine what each element will be. This is done passing a Ruby Array into ArrayList's constructor.
ArrayList.new Array(10) {|i| i*i}
Thanks to Mark Thomas for helping me think. :)
Upvotes: 1
Reputation: 3729
I don't think there is a way to do double curly brace initialization in JRuby. But for things like ArrayList Initialization JRuby offers shortcuts as in example below.
Please check https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby for details.
>> a = ArrayList.new [:a, :b, "c", "d"]
#<Java::JavaUtil::ArrayList:0x65a953>
>> a[0]
:a
>> a[1]
:b
>> a[2]
"c"
>> a[3]
"d"
>> a[4]
nil
Upvotes: 2