public
Created

Cleaned up Hash#fetch impl in JRuby

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
@JRubyMethod(compat = RUBY1_9)
public IRubyObject fetch(ThreadContext context, IRubyObject key, Block block) {
Ruby runtime = context.runtime;
 
IRubyObject value = internalGet(key);
if (value == null) {
if (block.isGiven()) return block.yield(context, key);
throw runtime.newKeyError("key not found: " + key);
}
return value;
}
@JRubyMethod(compat = RUBY1_9)
public IRubyObject fetch(ThreadContext context, IRubyObject key, IRubyObject _default, Block block) {
Ruby runtime = context.runtime;
boolean blockGiven = block.isGiven();
 
if (blockGiven) {
runtime.getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument");
}
 
IRubyObject value = internalGet(key);
if (value == null) {
if (blockGiven) return block.yield(context, key);
return _default;
}
return value;
}

Yes, this reads great.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.