From 16beaf00ce8a114227bb2bf845cb208913fefd9a Mon Sep 17 00:00:00 2001
From: "D.E. Akers" <0x0dea@gmail.com>
Date: Tue, 23 Jun 2015 20:59:09 -0400
Subject: [PATCH] Add String#bin for parity with #hex and #oct.
---
string.c | 22 ++++++++++++++++++++++
test/ruby/test_string.rb | 9 +++++++++
2 files changed, 31 insertions(+)
diff --git a/string.c b/string.c
index 4d2944c..b25ac26 100644
--- a/string.c
+++ b/string.c
@@ -7705,6 +7705,27 @@ rb_str_scan(VALUE str, VALUE pat)
/*
* call-seq:
+ * str.bin -> integer
+ *
+ * Treats leading characters from str as a string of binary digits
+ * (with an optional sign and an optional 0b
) and returns the
+ * corresponding number. Zero is returned on error.
+ *
+ * "1010".bin #=> 10
+ * "-0b111".bin #=> -7
+ * "2".bin #=> 0
+ * "12".bin #=> 1
+ */
+
+static VALUE
+rb_str_bin(VALUE str)
+{
+ return rb_str_to_inum(str, 2, FALSE);
+}
+
+
+/*
+ * call-seq:
* str.hex -> integer
*
* Treats leading characters from str as a string of hexadecimal digits
@@ -9153,6 +9174,7 @@ Init_String(void)
rb_define_method(rb_cString, "capitalize!", rb_str_capitalize_bang, 0);
rb_define_method(rb_cString, "swapcase!", rb_str_swapcase_bang, 0);
+ rb_define_method(rb_cString, "bin", rb_str_bin, 0);
rb_define_method(rb_cString, "hex", rb_str_hex, 0);
rb_define_method(rb_cString, "oct", rb_str_oct, 0);
rb_define_method(rb_cString, "split", rb_str_split_m, -1);
diff --git a/test/ruby/test_string.rb b/test/ruby/test_string.rb
index 2768a65..266f38a 100644
--- a/test/ruby/test_string.rb
+++ b/test/ruby/test_string.rb
@@ -303,6 +303,15 @@ class TestString < Test::Unit::TestCase
casetest(S("CaT"), S('cAt'), true) # find these in the case.
end
+ def test_bin
+ assert_equal(15, S("0b1111").bin)
+ assert_equal(-15, S("-0b1111").bin)
+ assert_equal(15, S("1111").bin)
+ assert_equal(-15, S("-1111").bin)
+ assert_equal(0, S("2").bin)
+ assert_equal(1, S("12").bin)
+ end
+
def test_capitalize
assert_equal(S("Hello"), S("hello").capitalize)
assert_equal(S("Hello"), S("hELLO").capitalize)
--
2.4.4