Is There a Short Way to Write '{|X| X}'

Is there a short way to write `{|x| x}`?

Yes. #itself was implemented in Ruby 2.2.0.


You can access the Ruby core team discussion about this feature here.

As an interesting analogue, the #ergo method has been proposed, which would yield the receiver to a given block.

If you haven't yet upgraded to Ruby 2.2.0, you may wish to backport #itself and/or define #ergo as follows:

class Object
def itself; self end
def ergo
fail ArgumentError, "Block expected!" unless block_given?
yield self
end
end

And then:

some_array.group_by &:itself

Is there a short elegant way to write variable providing with exception?

What you're asking is not very clear, so I don't know at which extent my answer will be meaningful.

If I understand well, you have fields of any type (Foo, Bar...) and you would like to instantiate them using whatever kind of provider you wish, which can throw an exception while providing.

So at first, I don't think that you should return if an exception is thrown by the provider, but rather re-throw it or handle it. Because if you had an exception while getting your Foo and so you actually don't have a Foo, why would you continue (or why wouldn't you try to handle it somehow)?

Now this said and assuming that re-throwing/handling is taken care of, then I would define a ThrowingSupplier functional interface:

@FunctionalInterface
public interface ThrowingSupplier<T, E extends Exception> {
T get() throws E;
}

... and then I would create a static method like this:

public static <T, E extends Exception> T provide(ThrowingSupplier<T, E> supplier) {
try {
return supplier.get();
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
throw (E) e;
}
}

So at that point, I would be simply calling this utility method every time that I want to execute such kind of operation:

Foo foo = provide(() -> FooProvider.getFoo(...)); //either creates a Foo, or prints and re-throw a FooProvidingException
Bar bar = provide(() -> BarProvider.getBar(...)); //either createa a Bar, or prints and re-throw a BarProvidingException
Integer myInt = provide(() -> 3);
String myStr = provide(() -> "hello");
//... and so on

But of course, at least once you'll have to extract the logic. Then it's all about extracting it in a way that it becomes generic and doesn't need to be repeated for each distinct type of object.

What does the construct x = x || y mean?

It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".

It's shorthand for writing:

if (!title) {
title = "Error";
}

This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:

a OR b

it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:

var title = title || "Error";

basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.

How to use hex() without 0x in Python?

(Recommended)

Python 3 f-strings: Answered by @GringoSuave

>>> i = 3735928559
>>> f'{i:x}'
'deadbeef'


Alternatives:

format builtin function (good for single values only)

>>> format(3735928559, 'x')
'deadbeef'

And sometimes we still may need to use str.format formatting in certain situations @Eumiro

(Though I would still recommend f-strings in most situations)

>>> '{:x}'.format(3735928559)
'deadbeef'

(Legacy) f-strings should solve all of your needs, but printf-style formatting is what we used to do @msvalkon

>>> '%x' % 3735928559
'deadbeef'

Without string formatting @jsbueno

>>> i = 3735928559
>>> i.to_bytes(4, "big").hex()
'deadbeef'

Hacky Answers (avoid)

hex(i)[2:] @GuillaumeLemaître

>>> i = 3735928559
>>> hex(i)[2:]
'deadbeef'

This relies on string slicing instead of using a function / method made specifically for formatting as hex. This is why it may give unexpected output for negative numbers:

>>> i = -3735928559
>>> hex(i)[2:]
'xdeadbeef'
>>> f'{i:x}'
'-deadbeef'

TypeScript: Index signature is missing in type

The problem is that when the type is inferred, then the type of o is:

{ dic: { a: number, b: number } }

That's not the same as { dic: { [name: string]: number } }. Critically, with the top signature you're not allowed to do something like o.dic['x'] = 1. With the 2nd signature you are.

They are equivalent types at runtime (indeed, they're the exact same value), but a big part of TypeScript's safety comes from the fact that these aren't the same, and that it'll only let you treat an object as a dictionary if it knows it's explicitly intended as one. This is what stops you accidentally reading and writing totally non-existent properties on objects.

The solution is to ensure TypeScript knows that it's intended as a dictionary. That means:

  • Explicitly providing a type somewhere that tells it it's a dictionary:

    let o: MyInterface

  • Asserting it to be a dictionary inline:

    let o = { dic: <{ [name: string]: number }> { 'a': 1, 'b': 2 } }

  • Ensuring it's the initial type that TypeScript infers for you:

    foo({ dic: { 'a': 1, 'b': 2 } })

If there's a case where TypeScript thinks it's a normal object with just two properties, and then you try to use it later as a dictionary, it'll be unhappy.

How to deal with PyCharm's Expected type X, got Y instead

PyCharm determines from the type-hints of the source code that the arguments you pass are incorrect.



How to disable

Your question simplifies to one of figuring out how to disable this type checking. However, please be warned,

Switching off the inspection completely is not a good solution. Most
of the time PyCharm gets it right and this provides useful feedback.
If it's getting it wrong, it's best to raise a ticket with them to see
if it can be fixed.

You can do that like this:

  1. Go to Settings/Preferences

  2. On the sidebar, click Inspections (under the Editor category)

  3. Expand the Python tab

  4. Scroll down to Type Checker and uncheck it

PyCharm should now stop issuing warnings about incorrect function arguments.

Is there a { |x| x } shorthand in ruby?

If you do not care about what is returned you can sometimes use the hash method.

Thw feature you are asking for is not available in Ruby yet, however. it is present in the Ruby road-map:

https://bugs.ruby-lang.org/issues/6373

Expected to be implemented before 2035-12-25, can you wait?

That being said, how much typing is group_by{|x|x} ?

Edit:

As Stefan pointed out, my answer is now longer valid for Ruby 2.2 and above since the introduction of Object#itself.

How to write a switch statement in Ruby

Ruby uses the case expression instead.

case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when "foo", "bar"
"It's either foo or bar"
when String
"You passed a string"
else
"You gave me #{x} -- I have no idea what to do with that."
end

Ruby compares the object in the when clause with the object in the case clause using the === operator. For example, 1..5 === x, and not x === 1..5.

This allows for sophisticated when clauses as seen above. Ranges, classes and all sorts of things can be tested for rather than just equality.

Unlike switch statements in many other languages, Ruby’s case does not have fall-through, so there is no need to end each when with a break. You can also specify multiple matches in a single when clause like when "foo", "bar".

Does ruby have an identity function, i.e. x.fn == x, for all x?

Yes. You're looking for Object#itself, which is available in Ruby 2.2+.

From the docs:

itself → an_object


Returns obj.

string = 'my string' #=> "my string"
string.itself.object_id == string.object_id #=> true


Related Topics



Leave a reply



Submit