Skip to content

Commit

Permalink
add binary number faker (#2166)
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielbaldao authored Mar 11, 2021
1 parent 9ebe104 commit 9f52ee9
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
3 changes: 3 additions & 0 deletions doc/default/number.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions lib/faker/default/number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand Down
6 changes: 6 additions & 0 deletions test/faker/default/test_faker_number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 9f52ee9

Please sign in to comment.