From 9f52ee9ad02f31e68314166c7c13fcf15bf1de0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Bald=C3=A3o?= Date: Thu, 11 Mar 2021 01:47:32 -0300 Subject: [PATCH] add binary number faker (#2166) --- doc/default/number.md | 3 +++ lib/faker/default/number.rb | 15 +++++++++++++++ test/faker/default/test_faker_number.rb | 6 ++++++ 3 files changed, 24 insertions(+) diff --git a/doc/default/number.md b/doc/default/number.md index e988828430..7f482e4ca0 100644 --- a/doc/default/number.md +++ b/doc/default/number.md @@ -27,6 +27,9 @@ Faker::Number.normal(mean: 50, standard_deviation: 3.5) #=> 47.14669604069156 # Keyword arguments: digits Faker::Number.hexadecimal(digits: 3) #=> "e74" +# Keyword arguments: digits +Faker::Number.binary(digits: 4) #=> "1010" + # Boundary numbers are inclusive # Keyword arguments: from, to Faker::Number.between(from: 1, to: 10) #=> 7 diff --git a/lib/faker/default/number.rb b/lib/faker/default/number.rb index 4b2bcba9cb..5ce20f7767 100644 --- a/lib/faker/default/number.rb +++ b/lib/faker/default/number.rb @@ -139,6 +139,21 @@ def hexadecimal(legacy_digits = NOT_GIVEN, digits: 6) hex end + # Produces a number in binary format. + # + # @param digits [Integer] Number of digits to generate the binary as string + # @return [String] + # + # @example + # Faker::Number.binary(digits: 4) #=> "1001" + # + # @faker.version next + def binary(digits: 4) + bin = '' + digits.times { bin += rand(2).to_s(2) } + bin + end + ## # Produces a float given a mean and standard deviation. # diff --git a/test/faker/default/test_faker_number.rb b/test/faker/default/test_faker_number.rb index d2eb2e0955..1343b062ac 100644 --- a/test/faker/default/test_faker_number.rb +++ b/test/faker/default/test_faker_number.rb @@ -128,4 +128,10 @@ def test_hexadecimal assert @tester.hexadecimal(digits: 4).match(/[0-9a-f]{4}/) assert @tester.hexadecimal(digits: 7).match(/[0-9a-f]{7}/) end + + def test_binary + assert @tester.binary(digits: 4).match(/^[0-1]{4}$/) + assert @tester.binary(digits: 8).match(/^[0-1]{8}$/) + assert @tester.binary.match(/^[0-1]{4}$/) + end end