我有两个像
这样的哈希h1 = {
DateTime.new(2015, 7, 1),in_time_zone => 0,
DateTime.new(2015, 7, 2).in_time_zone => 10,
DateTime.new(2015, 7, 4).in_time_zone => 20,
DateTime.new(2015, 7, 5).in_time_zone => 5
}
h2 = {
DateTime.new(2015, 7, 1).in_time_zone => 0,
DateTime.new(2015, 7, 2).in_time_zone => 0,
DateTime.new(2015, 7, 3).in_time_zone => 0
}
我想要合并h1
和h2
,如果密钥已经存在则不要合并,这样会产生类似的结果(带有时区的日期时间格式以便于阅读)
result
#=> {
# Wed, 01 Jul 2015 01:00:00 EST +01:00 => 0,
# Thu, 02 Jul 2015 01:00:00 EST +01:00 => 10,
# Fri, 03 Jul 2015 01:00:00 EST +01:00 => 0,
# Sat, 04 Jul 2015 01:00:00 EST +01:00 => 20,
# Sun, 05 Jul 2015 01:00:00 EST +01:00 => 5
# }
我尝试使用h1.merge(h2)
和h2.merge(h1)
,但可以将h2
的键和值设置为h1
。
答案 0 :(得分:1)
public static boolean validateWithExtXSDUsingSAX(String xml, String xsd)
throws ParserConfigurationException, IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI));
SAXParser parser = null;
try {
factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(xsd) }));
parser = factory.newSAXParser();
} catch (SAXException se) {
System.out.println("SCHEMA : " + se.getMessage()); // problem in the XSD itself
return false;
}
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.println("WARNING: " + e.getMessage()); // do nothing
}
@Override
public void error(SAXParseException e) throws SAXException {
System.out.println("ERROR : " + e.getMessage());
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("FATAL : " + e.getMessage());
throw e;
}
});
reader.parse(new InputSource(xml));
return true;
} catch (ParserConfigurationException pce) {
throw pce;
} catch (IOException io) {
throw io;
} catch (SAXException se) {
return false;
}
}
您将只有三个键值对,而不是您期望的5,因为Ruby中的哈希是唯一键的集合及其值。