Skip to content

Instantly share code, notes, and snippets.

@viatsko
Created October 22, 2017 21:01
Show Gist options
  • Save viatsko/730ce854515c5c8197673106b3938de7 to your computer and use it in GitHub Desktop.
Save viatsko/730ce854515c5c8197673106b3938de7 to your computer and use it in GitHub Desktop.
Parsing ruby single-dimension hash from java
import java.util.Map;
import java.util.HashMap;
public class ConvertRubySDHash {
public static Map<String, String> convertToObject(String line) {
Map<String, String> result = new HashMap<>();
for (int i = 0; i < line.length(); i++) {
while(i < line.length()) {
if (line.charAt(i) == '=' && line.charAt(i + 1) == '>') {
int end = i - 1; // before last quote
int j = end - 1;
while(line.charAt(j) != '"') {
j--;
}
String key = line.substring(j + 1, end);
int quotesFind = 0;
int k;
for (k = i + 2; k < line.length(); k++) {
if (line.charAt(k) == '=' && line.charAt(k + 1) == '>') {
while (k >= 0) {
if (line.charAt(k) == '"' && ++quotesFind == 2) {
k -= 2;
break;
}
k--;
}
}
if (quotesFind == 2) {
break;
}
}
String value;
if (quotesFind < 2) {
value = line.substring(i + 2, line.length());
} else {
value = line.substring(i + 2, k);
}
if (value.startsWith("\"")) {
value = value.substring(1, value.length() - 1);
}
result.put(key, value.equals("nil") ? null : value);
i = k + 2;
continue;
}
i++;
}
}
return result;
}
}
@viatsko
Copy link
Author

viatsko commented Oct 22, 2017

Not sure how useful it would be for someone, but as I didn't find any implementation around, I've written my own. It might be suboptimal, but worked very well for me to convert rails seed files :)

Example of input:

"id"=>4, "lat"=>52.3765396, "lng"=>4.9008333, "year_from"=>1888, "year_to"=>1999

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment